Ad
  • Custom User Avatar

    I don't think you're saving your sorted word. In any case, it is good practice to avoid clobbering the input values. Try saving your sorted word into a new variable and using that to compare.

  • Custom User Avatar

    Thanks for taking the time to explain all this in detail bkimmel, I really appreciate it. It took me awhile to understand but I finally think I got it. If you can pre-process (sort the words) then you can use the sorted word as a key in a hash and check if the words in the array are also the key in said hash.

  • Custom User Avatar

    whoops meant to reply here.

  • Custom User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Custom User Avatar

    function anagrams(word, words) {
    return words.filter(function(el) {
    return anagram(word, el);
    });
    }

    function anagram(word1, word2) {
    if (word1.length != word2.length) return false;
    var counts, length, char1, char2;
    counts = {};
    length = word1.length;

    for (var i=0; i < length; i++) {
    char1 = word1.charAt(i);
    char2 = word2.charAt(i);
    counts.hasOwnProperty(char1) ? counts[char1] += 1 : counts[char1] = 1;
    counts.hasOwnProperty(char2) ? counts[char2] -= 1 : counts[char2] = -1;
    }

    for (k in counts) if (counts[k] != 0) return false;
    return true;
    }

  • Custom User Avatar

    I did use the index trick to keep the anagram comparison linear. I'm not so sure there is a solution to find all the the anagram groups within an array that is better than O(n^2). Nonetheless I think I will make a kata around lunitik's suggestion and perhaps another to check for anagram solution complexity.

  • Custom User Avatar

    I wanted to write that kata initially but could not come up with my own elegant solution that is better than O(n^2). Not even sure if it can be done more efficiently.

  • Custom User Avatar

    If you want an additional challenge push for solution that doesn't use a sort.

    The fastest sorting algorithm is still n log n. If the two arrays to compare are very very very large then sorting them might take a long time. There is a solution that takes linear time.