OneBite.Dev - Coding blog in a bite size

Check if two strings is anagram on javascript

Here is how to solve the interview question for Check if two strings is anagram on javascript

What is anagram words?

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

Sample Code in javascript

To check if two strings are anagrams, one approach is to sort the characters in each string and then compare the sorted strings for equality. This approach assumes that two anagrams will have the same characters in the same quantities.

Here is a JavaScript function that implements this approach:

function areAnagrams(str1, str2) {
  // Remove any non-alphabet character and convert to lowercase
  str1 = str1.replace(/[^\w]/g, '').toLowerCase();
  str2 = str2.replace(/[^\w]/g, '').toLowerCase();

  return sortString(str1) === sortString(str2);
}

function sortString(str) {
  return str.split('').sort().join('');
}

console.log(areAnagrams('Listen', 'Silent')); // Should print: true
console.log(areAnagrams('Hello', 'World')); // Should print: false

Explanation

In this areAnagrams function, we first normalize the strings by removing any non-alphabet characters and converting to lowercase. We then compare the sorted versions of the strings. The sortString function sorts the characters in a string by splitting the string into an array, sorting the array, and then joining it back into a string.

Time Complexity Info

The time complexity of this function is O(n log n), where n is the length of the strings. This is because JavaScript’s Array.sort method has a time complexity of O(n log n). This is not the most efficient possible solution, but it is simple and works well for small strings.

Alternative Solution

A more efficient solution with a time complexity of O(n) would be to count the characters in each string and then compare the counts. However, this solution is more complex and involves more code.

← Determine if all string h...
Check if a string is pali... →
javascript