Skip to content
DSA Patterns
Menu
Language

Pattern #06

Hashing

Essential

O(1) average lookup, frequency counting, grouping, and complement checks.

When to use

You need fast membership, counts, or grouping by a derived key. especially when a nested loop would be O(n²).

Recognition cues

  • Two sum / complement to target
  • Anagram / frequency equality
  • Group by signature (sorted string, count tuple)
  • First unique, duplicates, longest consecutive (set)

Common pitfalls

  • Using list instead of set/map (O(n) lookup)
  • Mutable keys or unstable signatures
  • Hash collisions are rare; logic bugs in key design are common

90-second recognition drill

Which pattern fits best?

  • Two sum / complement to target
  • Anagram / frequency equality
  • Group by signature (sorted string, count tuple)

Interactive

Mental model

A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.

Step 1 of 8
1/8

Two Sum in one pass: ask for the complement before inserting.

2
0
7
1
11
2
15
3
map{ }
Statetarget=9seen={}

target = 9

Key:CurrentActive rangeMatchSettled

How to think about it

Trade space for time. Store what you have seen under a key that makes the next check O(1) on average. The key is the whole problem: a complement, a set membership, a 26-letter count, or a frequency bucket.

Template shapes

Shape Key Example
Complement Look up target - value before storing the current index, so a value is not paired with itself LC 1
Membership Insert into a set. Already present means a duplicate. A consecutive run starts only when x - 1 is missing LC 217, LC 128
Frequency 26 letter counts, or sort both strings. Different lengths are false before counting LC 242
Group by signature The key is the 26 counts or the sorted characters. An empty word is its own group LC 49
Frequency buckets Count each value, then buckets indexed by that count. Read from the high end until k values. The highest count is at most n LC 347

Complexity baseline

Average O(n) time and O(n) space. Worst-case hash behavior is rarely the interview focus. The key design is.

From template to problem

  1. Name the key before the loop. A count tuple and a sorted string group the same anagrams (LC 49).
  2. For a complement, query the map before the insert (LC 1). Inserting first makes a value match itself.
  3. For a consecutive run, skip x when x - 1 is already in the set (LC 128). Duplicate copies of x do not extend the run.
  4. Top-k by frequency on this path is buckets, not a heap. The bucket index is the count, and the count cannot exceed n (LC 347).

Template

Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.

Hashing · Template
/** Hashing template: Two Sum with a value→index map. */
export function twoSum(nums: number[], target: number): number[] {
  const seen = new Map<number, number>();
  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i]!;
    if (seen.has(need)) return [seen.get(need)!, i];
    seen.set(nums[i]!, i);
  }
  throw new Error("No solution");
}
/** Hashing template: Two Sum with a value→index map. */
export function twoSum(nums: number[], target: number): number[] {
  const seen = new Map<number, number>();
  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i]!;
    if (seen.has(need)) return [seen.get(need)!, i];
    seen.set(nums[i]!, i);
  }
  throw new Error("No solution");
}
#StatusProblemTypeDone
  1. 1#1 Two SumGuide
  2. 2#49 Group AnagramsGuide
  3. 3#128 Longest Consecutive SequenceGuide
  4. 4#217 Contains DuplicateGuide
  5. 5#242 Valid AnagramGuide
  6. 6#347 Top K Frequent ElementsGuide