× logo Home HTML CSS Javascript React-App Angular logo
logo

Mastering Top 10 Javascript Algorithms





**Algorithm Name**: Anagram Validation

* **Questions**:
Are the strings case sensitive? Are the strings ASCII or Unicode strings? Are white spaces in the strings considered?

* **Time Complexity**:
- Both the "optimized" and "brute force" will give you the same result in this case: O(n log n) because a sort operation has a time complexity of O(n log n) where 'n' is the length of the string.

* **Space Complexity**:
- The space complexity is O(n) because we are creating extra string representations of the same length as the input strings.

* **Approaches**:
* **Optimized**:
In this case, the most efficient approach is to split the strings into individual characters, sort them and then join them back into strings. After this, you compare the two strings for equality.

* **Brute Force**:

You could create a histogram for each string (count the number of each character). Then compare the histograms to see if they have the same counts for each character. This can be much slower and more complex, but gives an alternative approach to consider.

* **Explanation**:
- For an anagram, when the characters of two strings are rearranged, they become the equal to each other.

Based on this property, we sort the strings alphabetically and then compare them for equality.

If the strings are equal after sorting, then they are anagrams of each other.

* **Sample Code**:JavaScript

const anagram = (s1, s2) => {
// Split the string into an array of individual characters
// Sort the array in alphabetical order
// Join the sorted array back into a string
// Do this for both strings and then compare if the result is the same

return s1.split("").sort().join("") === s2.split("").sort().join("");
}

* **Example**:
- Input: "mary", "army"
- Output: true

**Unit Test
Input and Output**
console.log(anagram("mary", "army")); // true
console.log(anagram("listen", "silent")); // true
console.log(anagram("hello", "




logo