Data Structures19 sections · 729 units
Open in Course

Group Anagrams - Implementation

Complete solution

Here's the solution using sorted keys:

function groupAnagrams(strs)
    groups := empty hash map  // sorted string -> list of strings

    for each str in strs
        key := sort characters of str
        if key not in groups
            groups[key] := empty list
        append str to groups[key]

    return all values in groups

Time: O(nklogk)O(n \cdot k \log k) where nn is the number of strings and kk is the maximum string length. Space: O(nk)O(nk).