Group Anagrams

mediumTests passed 2026-11-11v1.0.0

1. Core Invariant / The Trick

Canonicalize every string to its 26-letter frequency signature (avoiding K log K sorting overhead per string) and bucket strings sharing the identical signature.

2. Complexity Bounds & Proof

N strings each of max length K are hashed into a 26-bin frequency tuple in O(K) time.

3. Minimal Idiomatic Code

def groupAnagrams(strs: list[str]) -> list[list[str]]:
    groups = defaultdict(list)
    for s in strs:
        cnt = [0] * 26
        for c in s:
            cnt[ord(c) - 97] += 1
        groups[tuple(cnt)].append(s)
    return list(groups.values())

4. Failure Modes & Interview Follow-ups

Pitfalls:- Forgetting separator delimiters when serializing counts (`[1, 12]` vs `[11, 2]`).
Follow-ups:- Large strings: sort or rolling hash vs prime product (watch overflow on prime products).

Personal Notes & Scratchpad (Local-First Yjs CRDT)

Saved instantaneously in IndexedDB. Streams live across peers via Hocuspocus when signed in.

Related Invariants

Browser Scratchpad
Console Output
Click Run or press Cmd/Ctrl+Enter to execute locally in a Web Worker.