DSA Tracker

Problem

Pattern this teaches:Hashing and Frequency Maps

Medium

Group Anagrams

A medium Strings interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Strings
Sheets
3
Core for
14 roles

The problem

Group an array of strings together such that all anagrams reside in the same bucket.

Example 1

Input
strs=["pots","tops","cat","act","stop","dog"]
Output
[["dog"],["act","cat"],["pots","stop","tops"]]
Why
Words made of exactly the same letters land in one group: pots, stop and tops share o, p, s, t; act and cat share a, c, t; dog stands alone.

Example 2

Input
strs=[""]
Output
[[""]]
Why
A single empty string forms its own isolated group.

Example 3

Input
strs=["a"]
Output
[["a"]]
Why
A single one-letter string forms its own single-element group.

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters

How to think about it

Updated 2026-09-29

Anagrams are permutations of each other, meaning they map to an identical canonical signature. By transforming each word into a unique hashable representation, either its sorted character sequence or a fixed-size character count vector, words with matching content collapse into the same dictionary key.

Approaches, worst first

  1. Pairwise anagram search

    time O(n^2 * k) · space O(n * k)

    Compare each word against every previously formed bucket by checking if it is an anagram of the bucket's representative. Checking anagram equivalence against buckets requires quadratic word comparisons.

  2. Categorize by sorted string key

    time O(n * k log k) · space O(n * k)

    Sort the characters of each string to form a canonical key, and push the original word into a hash map indexed by this key. Sorting each string of length k takes O(k log k), dominating the hash map lookup.

  3. Categorize by character count tupleWrite this one

    time O(n * k) · space O(n * k)

    Count character frequencies into a 26-element array for each string, convert that frequency array into an immutable tuple or serialized delimiter key, and group items in a hash table. Eliminates the sorting cost per word entirely.

Where people lose marks · 3
  • String key delimiter collisions: serializing frequency counts like [1, 11] versus [11, 1] without a delimiter causes distinct frequency signatures to merge into the same hash key.
  • Empty string inputs: an array containing multiple empty strings like ["", ""] must group them into a single group ["", ""], rather than crashing key generation.
  • Mutating the original strings: sorting characters in place when an array is passed by reference can corrupt the caller's input data if not copied or handled properly.

Full solution

Character-count tuple as a hash key: O(n*k) with no per-word sort, and it handles empty strings and single letters as ordinary keys with no special-casing.

Python
from collections import defaultdict
from typing import List


def group_anagrams(words: List[str]) -> List[List[str]]:
    groups: dict[tuple, List[str]] = defaultdict(list)
    for word in words:
        counts = [0] * 26
        for ch in word:
            counts[ord(ch) - ord("a")] += 1
        # a 26-length count tuple is a collision-free key: no delimiter to get wrong
        groups[tuple(counts)].append(word)
    return list(groups.values())
JavaScript
function groupAnagrams(words) {
  const groups = new Map();
  for (const word of words) {
    const counts = new Array(26).fill(0);
    for (const ch of word) counts[ch.charCodeAt(0) - 97]++;
    const key = counts.join(","); // comma delimiter avoids the [1,11] vs [11,1] collision
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(word);
  }
  return Array.from(groups.values());
}
Try it in the editor

The theory behind it

Strings — the ground this problem stands on. All Strings problems

What Strings is

A string is an ordered necklace of text characters, like letters printed along a ribbon of paper. Each character sits at an exact numeric slot, holding a glyph such as a letter, punctuation mark, or digit. In many programming languages, ribbons cannot be edited after creation, meaning changing a single character requires pressing an entirely new ribbon from scratch.

When to reach for it

Reach for string techniques when inputs consist of words, DNA sequences, serialized data formats, or sentences. Clues include questions testing palindromes, anagram matches, substring patterns, parenthesis balancing, or character frequency counts. Whenever an algorithm asks to transform capitalization, parse structured tokens, or compute edits between two phrases, string representations are the core subject.

How the pattern works

Think of characters as small integer codes ranging across standard character sets. Frequency tables with fixed sizes often replace heavy hash maps when tallying occurrences. For search tasks, maintain rolling state using character indices or sliding borders. When building output text through repeated appends, accumulate pieces inside a mutable list or string builder rather than concatenating strings directly, avoiding quadratic copy overhead.

More Strings problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .