An interactive visualization of how a hash map groups anagrams by their sorted canonical key. Watch strings get sorted, hashed, and placed into groups step by step.
Hash Map LeetCode 49 ↗ Mediumstrs, group the anagrams together. You can return the answer in any order.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()}
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".
groups where keys are sorted strings and values are lists of original strings.
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.