We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Array letters is of length 26, and stores the "frequencies" of letters in the string one. We index the array by the distance from the letter 'a'. So in letters['a'-'a']=letters[0] we will store the number of a's in string one.
letters['b'-'a']=letters[1] the number of b's
letters['g'-'a']=letters[6] the number of g's and so on.
letters[c-'a']++ is a postfix notation and means the same as letters[c-'a']=letters[c-'a']+1, so we just encountered a letter and we add 1 to the corresponding slot.
Same with letters[c-'a']--, but this time we subtract all the frequencies in the string two. This way, if there were 3 d's in string one and 5 d's in string two, the 4th slot in letters will be letters[3]=-2, but then we take care of it, by applying Math.abs
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Strings: Making Anagrams
You are viewing a single comment's thread. Return to all comments →
Array
letters
is of length 26, and stores the "frequencies" of letters in the stringone
. We index the array by the distance from the letter 'a'. So in letters['a'-'a']=letters[0] we will store the number of a's in stringone
.letters['b'-'a']=letters[1] the number of b's
letters['g'-'a']=letters[6] the number of g's and so on.
letters[c-'a']++ is a postfix notation and means the same as letters[c-'a']=letters[c-'a']+1, so we just encountered a letter and we add 1 to the corresponding slot.
Same with letters[c-'a']--, but this time we subtract all the frequencies in the string
two
. This way, if there were 3 d's in stringone
and 5 d's in stringtwo
, the 4th slot inletters
will be letters[3]=-2, but then we take care of it, by applyingMath.abs