Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 30, 2022 09:33 pm GMT

JavaScript LeetCode Valid Anagram

Prompt

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.

Example 1:

Input: s = "anagram", t = "nagaram" Output: true

Analyzing the problem

Lets this of what the problem is asking. We have to know the contents of the strings were analyzing. We also have to make sure that were keeping track of the letters as they should be exactly the same to confirm that it is an anagram.

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 its 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:

javascript leetcode

Looking at the counts we can use this to validate in place as we iterate over the second word. Lets see how this would look:

javascript leetcode

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 are not valid anagrams.

Cool , lets get to coding.

The solution

Similar to our last problem we can use a hash table.

var isAnagram = function(s, t) {    if (s.length != t.length) return false;    const hashTable = {};    for(let i = 0; i < s.length; i++) {        if (!hashTable[s[i]]) {          hashTable[s[i]] = 0;        }        hashTable[s[i]]++;    }    for(let j = 0; j< t.length; j++) {        if (!hashTable[t[j]]){          return false;          }         hashTable[s[j]]--;     }    return true;};

In the first iteration, we add the frequency of every letter. If it doesnt 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 well hit the number 0 which means we'll return a false.

if (!hashTable[t[j]]){   return false;  } hashTable[s[j]]--;

Lets connect

If you liked this feel free to connect with me on LinkedIn or Twitter

Check out my free developer roadmap and weekly tech industry news in my newsletter.


Original Link: https://dev.to/diballesteros/javascript-leetcode-valid-anagram-2001

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To