The Problem

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.

Interactive Visualization

Speed:
Input Strings
Sorting — Canonical Key
Select a string to see its sorted key
Hash Map — Anagram Groups
Groups will appear here as strings are processed
Status
Press Step or Play to begin.
Code
fun groupAnagrams(strs: Array<String>): List<List<String>> {    val groups = mutableMapOf<String, MutableList<String>>()    for (s in strs) {        val key = String(s.toCharArray().apply { sort() })        if (key !in groups) {            groups[key] = mutableListOf()        }
        groups[key]!!.add(s)    }    return groups.values.toList()}

How It Works

Key Insight

Two strings are anagrams if and only if they contain the same characters in the same frequencies. Sorting a string gives a canonical form — all anagrams produce the same sorted key. For example, "eat", "tea", and "ate" all sort to "aet".

The Algorithm

  • Initialize: create an empty hash map groups where keys are sorted strings and values are lists of original strings.
  • For each string: sort it to produce the canonical key.
  • Group: if the key is not yet in the map, create a new empty list. Then append the original string to the list for that key.
  • Return: all the values (lists) from the hash map.

Complexity

Time O(n · k log k)
Space O(n · k)

Where n is the number of strings and k is the maximum string length. We sort each string in O(k log k) and do this for all n strings. The hash map stores all n strings, each up to length k.