Sherlock and Anagrams

  • + 0 comments

    Solution in JS, Create a Map with all the consecutives substrings, and sort each one to simplify the search in the map, and use the acumulation to simplify the last sumatory,

    function sherlockAndAnagrams(s) {
        // Write your code here
        
        let out = 0;
        let hash = {}
        for (let i = 0; i < s.length; i++){
            for (let j = i+1; j < s.length + 1; j++){
                let c = [...s.substring(i, j)].sort().join('');
                console.log(c, hash[c])
                out += hash[c] || 0
                if(c in hash) hash[c]++
                else hash[c] = 1;
            }
        }
        return out
    }