Leetcode Practice

LC 242. Valid Anagram

Last updated
Reading time
2 min read

The problem

Solution

Sorting each string alphabetically and checking if they are equal does the trick here, given that the words are assumed to have the same number of letters. Note that it also assumes that the strings are alphabetical.

function isAnagram(s: string, t: string): boolean {
  return s.split('').sort().join('') === t.split('').sort().join('')
}

Without those builtin methods, it could also be solved with a hashmap like this:

function isAnagram(s: string, t: string): boolean {
  if (s.length !== t.length) return false
  let map = {}
  for (let i = 0; i < s.length; i++) {
    if (map[s[i]]) {
      map[s[i]]++
    } else {
      map[s[i]] = 1
    }
  }

  for (let i = 0; i < t.length; i++) {
    if (!map[t[i]]) {
      return false
    } else {
      map[t[i]]--
    }
  }

  return true
}

Follow Up Problem

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Solution

I'm not certain on this, but from a few tests it seems either of the solutions I wrote previously will work. I was confused by this follow up and read on MDN's documentation about how localeCompare is required to sort these correctly. However, for the purposes of this problem the sort order doesn't actually matter as long as the results are the same for both strings.