DSA Visualizer · 25 visualizationsGroup Anagrams
MediumArrays & Hashing

Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order. Two strings are anagrams if one is a rearrangement of the other's characters.

The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(n·k log k) · space O(n·k)
def groupAnagrams(strs: list[str]) -> list[list[str]]:
    from collections import defaultdict
    groups = defaultdict(list)
    for s in strs:
        groups[tuple(sorted(s))].append(s)
    return list(groups.values())
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough