JavaScript Algorithm to find all possible anagram of a string

JavaScript Algorithm to find all possible anagram of a string.

let genAnagrams = (word, n, anagram  = '', anagrams = []) => {
    word = word.toUpperCase();
    if(anagram) {
        anagrams.push(anagram)
    }
    if(!word) {
        return
    }
    for(let i=0; i<word.length; i++) {
        anagram += word[i];
        genAnagrams(word.slice(0,i) + word.slice(i+1), n, anagram, anagrams);
        anagram = anagram.slice(0 , anagram.length-1)
    }
    let uniq =  [...new Set(anagrams)];
    let hashMap = {}

    for(let i=0; i<uniq.length; i++){
        anagram = uniq[i];
        let len = anagram.length;
        if(!(len in hashMap) ){
            hashMap[len] = [anagram];
        } else {
            hashMap[len].push(anagram);
        }
    }
    return n === null ? uniq : hashMap[n];
}

console.log(genAnagrams('ABCDEFG', 6))

Credit Link

Leave a Reply

Your email address will not be published. Required fields are marked *