Pep
Pep

Reputation: 677

IsAnagram, why - 97? - Javascript

I am trying to understand this isAnagram algorithm where two words need to have the same length and the same letters, Does anybody know why the -97 is required? Where does that number come from?

Why does it necessarily have to be the number 97?

var isAnagram = function(s, t) {
    if (s.length !== t.length) return false;
    
    let checkArray = new Array(26).fill(0);
    
    for (let i = 0; i < s.length; i++) {
        checkArray[s.charCodeAt(i) - 97]++;
    }
    
    for (let x = 0; x < t.length; x++) {
        checkArray[t.charCodeAt(x) - 97]--;
    }
    
    for (let k = 0; k < 26; k++) {
        if (checkArray[k] !== 0) return false;
    }
    
    return true;
    
};

console.log('Anagram: ', isAnagram("anagram","nagaram"))

Upvotes: 2

Views: 110

Answers (1)

Yakov Galka
Yakov Galka

Reputation: 72449

97 is the ASCII code for the lower-case letter 'a'. By subtracting 97 it maps the lowercase alphabet a-z to the integers 0..25, which are the valid indexes in the allocated array.

It is not strictly speaking required. You could use a bigger array (e.g. of size 128) to handle all of ASCII. Then you won't need to subtract anything.

Upvotes: 3

Related Questions