Skip to main content

< Back to Data Structures and Algorithms

LeetCode 242 · Strings

Valid Anagram

Whether two words use exactly the same letters: counted up through the first, back down through the second.

Step through it

Examples
Edge cases
s
  1. a0
  2. n1
  3. a2
  4. g3
  5. r4
  6. a5
  7. m6
t
  1. n0
  2. a1
  3. g2
  4. a3
  5. r4
  6. a5
  7. m6

Step 0 of 14

Output

Running… play or step to the end.

The code

/**
 * Determines if two strings are valid anagrams of eachother.
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
 const isAnagram = (s, t) => {
  // Edge case: String lengths don't match, can't be valid.
  if (s.length !== t.length) return false

  /* Stores each chatacter as a key, and each value as 
     an integer to count the number of occurences for that character. */
  const charDict = {}
  
  // O(n) loop over the first string.
  for (let i=0; i < s.length; i++) {
      // Store the character in the dictionary if it doesn't exist.
      if (!charDict[s[i]]) {
          // Set the initial value of the character to 1.
          charDict[s[i]] = 1
      // The character is already stored.
      } else {
          // Increment the value by 1.
          charDict[s[i]]++
      }
  }
  
  // O(n) loop over the second string.
  for (let i=0; i < t.length; i++) {
      // If the character does not exist.
      if (!charDict[t[i]]) {
          // This is NOT an anagram of the first string.
          return false
      } else {
          // Character match found, decrement its value in the dictionary.
          charDict[t[i]]--
      }
  }

  // O(n) loop over the character dictionary
  for(let key in charDict) {
      // If the value of the character is not 0, it is not an anagram.
      if (charDict[key] !== 0) return false
  }
  
  // Both strings are anagrams of eachother.
  return true    
}

View it on GitHub (opens in a new tab)