Ads Top

Interview Practice: Javascript Valid Anagram Solution

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. If you have the following two words:

Notes | Stone

With these two words you can see weare able to rearrange Stone to give you Notes
You can also rearrange Notes to give you Stone.

There are a few ways to solve this programattically but i prefer the method using these steps for a javascript solution.

1: Split each word by letter into an array using the split() function.
2: Sort the letters using the sort() function
3: Once the array of letters (of the word) are sorted, you can then do toString() in order to convert the array back to a word

Steps 1 - 3 can be done in one line
s.split("").sort().toString()

Once you have these two values, you can then compare the results. If they are equal, then you have an anagram.

All together, the solution is as follows:
Program Output
Results ...
"nagaram" is an anagram of "anagram"
"totes" is NOT an anagram of "notes"
"stone" is an anagram of "notes"

Leetcode anagram problem https://leetcode.com/problems/valid-anagram/

No comments:

Powered by Blogger.