← DSA practice

Group Anagrams

MediumStrings · HashingO(n · k log k) time · O(n · k) space

The problem

Group a list of words so that all anagrams of each other are in the same group. Return the groups in any order.

["eat","tea","tan","ate","nat","bat"]
→ [["eat","tea","ate"], ["tan","nat"], ["bat"]]
Stuck? Open one hint

Two anagrams must produce the same value under some function. Find that function and you have your map key.

Show the worked solution

All you need is a canonical form that is identical for anagrams. Two common choices:

  • Sorted characters — "eat" and "tea" both become "aet". Simple, O(k log k) per word.
  • Count signature — a 26-length count turned into a string. O(k) per word, better when words are long.

Then it is one pass into a HashMap<String, MutableList<String>>. Offer both and say which you would pick given the input size — that is the senior answer.

fun groupAnagrams(words: Array<String>): List<List<String>> {
    val groups = HashMap<String, MutableList<String>>()
    for (word in words) {
        val key = word.toCharArray().apply { sort() }.concatToString()
        groups.getOrPut(key) { mutableListOf() }.add(word)
    }
    return groups.values.toList()
}

O(n · k log k) time · O(n · k) space