algorithm Check two strings are anagrams Sample input and output


Example

Ex1:-

let str1 = 'stackoverflow';
let str2 = 'flowerovstack';

These strings are anagrams.

// Create Hash from str1 and increase one count.

hashMap = {
    s : 1,
    t : 1,
    a : 1,
    c : 1,
    k : 1,
    o : 2,
    v : 1,
    e : 1,
    r : 1,
    f : 1,
    l : 1,
    w : 1
}

You can see hashKey 'o' is containing value 2 because o is 2 times in string.

Now loop over str2 and check for each character are present in hashMap, if yes, decrease value of hashMap Key, else return false (which indicate it's not anagram).

hashMap = {
    s : 0,
    t : 0,
    a : 0,
    c : 0,
    k : 0,
    o : 0,
    v : 0,
    e : 0,
    r : 0,
    f : 0,
    l : 0,
    w : 0
}

Now, loop over hashMap object and check all values are zero in the key of hashMap.

In our case all values are zero so its a anagram.