InterviewHubPRO
Section Overview
Q8

Question 8 of 100

Part 2: Arrays, Strings & Hash Maps (6 - 18)

8%
DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)

Group Anagrams.

In Simple Words: Sort each word's characters alphabetically to create a canonical key. Group words with the same sorted key together into a Hash Map.

  • Time: $O(N \cdot K \log K)$ | Space: $O(N \cdot K)$
Multi-Language Solutions
Switch tabs or choose All
from collections import defaultdict

def groupAnagrams(strs: list[str]) -> list[list[str]]:
    ans = defaultdict(list)
    for s in strs:
        key = "".join(sorted(s))
        ans[key].append(s)
    return list(ans.values())