We will maintain a table,count containing an entry for every letter possible in our string ... Lets assume only 5 letters are possible in any string and they are a,b,c,d,e
Assume i have 2 strings "abc" and "cba" ... On seeing we can say definitely both are anagrams of each other ...Now lets see how this algorithm makes sure it is an anagram ...
Count table initially
a's entry |
b's entry |
c's entry |
d's entry |
e's entry |
0 |
0 |
0 |
0 |
0 |
Now I will scan both the strings, one letter at a time
On scanning 1 st letter of both strings, string 1 will make a's entry as 1 and string 2 will make c's entry as -1
On scanning 2 nd letter of both strings, string 1 will make b's entry as 1 and string 2 will modify b's entry from 1 to 0
On scanning 3 rd letter of both strings, string 1 will modify c's entry from 1 to 0 and string 2 will modify a's entry from 1 to 0
So after scanning all 3 strings, the entire count array will be full of 0's... So it is an anagram .. Incase if even one entry is not 0, then definitely it is not an anagram ...
Now in we have j++ just to move from 1 st letter to 2 nd letter , 2nd letter to 3 rd letter and so on ... So A) and B) are eliminated for this reason ...
C) is eliminated because only after scanning both the string's 1 st letter, I need to increment j (to move to the 2 nd letter) ... But Option C) after scanning 1 st letter of 1 st string increments j thus not allowing 1 st letter of 2 nd string to update the count table ...