Checking the Frequency of Certain Values


Question & Examples

Given two strings, write a function to determine if the second string is an anagram of the first. An anagram is a word, phrase, of name formed by rearranging the letters of another, such as cinema, formed from iceman.

// examples
"aax", "aaa" // false
"heheh", "heheh" // true
"hello", "hell" // false
" ", " " // true

My Solution

function validAnagram(str1, str2) {
  // check the lengths of the two strings first
  if(str1.length !== str2.length) {
    return false
  }
  // create an object
  const frequencyCounter1 = {}
  const frequencyCounter2 = {}
  
  // assign each letter as a key in the object
  // then set the value of said key by +1 every time
  // it's in the string
  for(let val of str1) {
    frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1
  }
  for(let val of str2) {
    frequencyCounter2[val] = (frequencyCounter2[val] || 0) + 1
  }
 
  for(let key in frequencyCounter1) {
    // while looping over the first object,
    // check to see if the keys in both objects
    // are the same
    if(!(key in frequencyCounter2)) {
      return false
    }
 
    // then, check to see if the key's values are the
    // same as well
    if(frequencyCounter1[key] !== frequencyCounter2[key]) {
      return false
    }
  }
  // return true if everything passes
  return true
}

Time Complexity: O(n)


Go back to list