
Posted on • Originally published atrelatablecode.com on
JavaScript LeetCode Valid Anagram
Prompt
AnAnagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Analyzing the problem
Let’s this of what the problem is asking. We have to know the contents of the strings we’re analyzing. We also have to make sure that we’re keeping track of the letters as they should be exactly the same to confirm that it is ananagram.
Following that train of thought, we can early return if there is ever a difference in the letters they contain. But what does it mean to have the same letters? Well, essentially it’s mapping out the frequency of each letter for the first word we iterate over. When we iterate over the second word we can double-check with what.
Checking back on the first example provided we can visualize this by counting each letter:
Looking at the counts we can use this to validate in place as we iterate over the second word. Let’s see how this would look:
So the first time we run into the n in the second iteration we subtract it from the count. Anytime we go below 0 then we know the words arenot valid anagrams.
Cool 😎, let’s get to coding.
The solution
Similar to ourlast problem we can use a hash table.
varisAnagram=function(s,t){if(s.length!=t.length)returnfalse;consthashTable={};for(leti=0;i<s.length;i++){if(!hashTable[s[i]]){hashTable[s[i]]=0;}hashTable[s[i]]++;}for(letj=0;j<t.length;j++){if(!hashTable[t[j]]){returnfalse;}hashTable[s[j]]--;}returntrue;};
In the first iteration, we add the frequency of every letter. If it doesn’t exist we create a 0 value at that point.
if(!hashTable[s[i]]){hashTable[s[i]]=0;}hashTable[s[i]]++;
On the second iteration, we subtract all values. If no letter ever exists then we’ll hit the number 0 which means we'll return a false.
if(!hashTable[t[j]]){returnfalse;}hashTable[s[j]]--;
Let’s connect
If you liked this feel free to connect with me onLinkedIn orTwitter
Check out my free developer roadmap and weekly tech industry news in mynewsletter.
Top comments(2)

- LocationBangkok 🇹🇭
- Joined
constisAnagram=(s,t)=>''+[...s].sort()==[...t].sort()

- LocationBogota D.C., Colombia
- WorkSenior Developer
- Joined
Nice, I like the one liner!
For further actions, you may consider blocking this person and/orreporting abuse