#49
Medium
Prefix Sum

Group Anagrams

Group strings that are anagrams of each other.

StringHash Table

Pattern fit

The core is designing a canonical signature for character counts, which is a cousin of prefix/frequency counting rather than a traversal problem.

Key observation

Two strings belong to the same group exactly when their normalized character-count signatures match.

Target complexity

O(total chars) / O(n)

How to break down the solution cleanly

1

The core is designing a canonical signature for character counts, which is a cousin of prefix/frequency counting rather than a traversal problem.

2

Two strings belong to the same group exactly when their normalized character-count signatures match.

3

Define what the cumulative state means.

4

Build the prefix in one forward pass.

Reference implementation

Python
# Generic pattern template
prefix = [0] * (len(nums) + 1)
for i, value in enumerate(nums):
    prefix[i + 1] = prefix[i] + value

range_sum = prefix[r + 1] - prefix[l]

Common pitfalls

warning

Using the unsorted string itself as the key.

warning

Building a key that is ambiguous across different count tuples.

Common follow-ups

Would sorted-string keys or count-vector keys be better here?

How would this change for Unicode-heavy inputs?

Continue with related problems

Build repeatable depth inside the Prefix Sum cluster before moving on.

view_weekBack to the pattern page
LeetCode 49. Group Anagrams Guide | Interview AiBox