Verify if two words are anagram using JavaScript

Verify if two words are anagram using JavaScript

Anagram Solution in JavaScript

Algorithm challenge: find anagram words. Learn how you can write a function/algorithm to find the check if two words are anagrams of each other.

What is an anagram?

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. This is typically done by using all the original letters exactly once.

Examples of anagrams

  • Dusty = Study
  • Tar = Rat
  • Arc = Car
  • State = Taste
  • Cider = Cried
  • Bored = Robed
  • Elbow = Below
  • Cat = Act
  • Save = Vase

The challenge

Write a function that takes in two string/words and returns true if the words are anagrams of each other, otherwise, it returns false.

Solution

Please note that the solution does not cover the possible edge cases or assumptions.

/**
 *
 * Checks if two strings are anagrams of each other
 *
 * @param {string} str1 a string
 * @param {string} str2 a string
 * @return {boolean}
 */
function areAnagram(str1, str2) {
  // the string lengths must be equal
  if (str1.length !== str2.length) {
    return false;
  }

  // put both strings in uppercase for 
  // case insensitive comparison
  str1 = str1.toUpperCase();
  str2 = str2.toUpperCase();

  // iterate over each of the strings keeping a
  // count of each character in the string in an object
  const obj1 = {};
  const obj2 = {};

  for (let i = 0; i < str1.length; i++) {
    const key = str1.charAt(i);
    obj1[key] = (obj1[key] || 0) + 1;
  }

  for (let i = 0; i < str2.length; i++) {
    const key = str2.charAt(i);
    obj2[key] = (obj2[key] || 0) + 1;
  }

  // iterate over one of the counter objects and check that the count of
  // each character in the object is the same count in the other object
  // return false if not equal
  for (const key in obj1) {
    if (obj1[key] != obj2[key]) {
      return false;
    }
  }

  // else, return true
  return true;
}

areAnagram('Cat', 'Acting'); // false
areAnagram('Dusty', 'Study'); // true
areAnagram('Arc', 'Car'); // true
areAnagram('Cider', 'Cried'); // true

Time Complexity

The time complexity of the solution above is O(n). Notice that we have 3 loops but no nested loops. Of course you can find even a better solution to this problem. What I have written here is a feasible solution but not necessarily the best.

 

Leave a Reply

Your email address will not be published. Required fields are marked *