Arrays & Hashing Pattern

← All learning paths

Learn when an array scan should carry a set, map, or reusable prefix state—and when another pattern is the better choice.

Your pattern progress

0/5 solved

Start: Contains Duplicate

Recognition cues

Use a set or map when you need to:

  • detect a value seen before;
  • count, group, or compare frequencies;
  • find a complement during one pass;
  • reuse prefix information instead of rescanning.

When not to use it

  • Contiguous ranges may need a sliding window.
  • Sorted input may favor two pointers or binary search.
  • Nested choices may need dynamic programming or backtracking.
  • Strict O(1) space rules out an auxiliary map unless values are bounded.

Core mental model

Scan once and keep only past information that answers a future question. Before index i, the map or set summarizes exactly the processed prefix; after processing it, the same invariant holds for the next index.

Typical time: O(n)
Typical space: O(n)
Sorting alternative: O(n log n)

Worked example: Two Sum

Input [2, 7, 11, 15], target 9. Check the complement before storing the current value.

Index/valueNeededSeenDecision
0 / 27{}Store 2 → 0
1 / 72{2: 0}Found; return [0, 1]

Invariant: seen contains exactly the values before i, so one item cannot be used twice.

Common failure modes

  • Storing before checking and reusing the current item.
  • Using a set when the answer needs an index or count.
  • Overwriting duplicate information too early.
  • Calling O(n) map storage O(1) space.
  • Assuming hashing is ordered or worst-case constant time.

Prerequisite order

  1. One-pass array traversal and indices.
  2. Set membership and duplicate behavior.
  3. Map reads, writes, missing keys, and counts.
  4. Time/space analysis for scans, hashing, and sorting.
Review foundations →

Easy → medium → timed check

Solve in order; each step adds one decision to the same prefix-summary model.

1. Contains Duplicate

Easy

Set membership

2. Valid Anagram

Easy

Frequency counting

3. Two Sum

Easy

Complement lookup

4. Product of Array Except Self

Medium

Prefix and suffix state

5. Top K Frequent Elements

Medium

Count, then rank

Final timed check

Run a 30-minute Arrays & strings mock; state the invariant before coding, then finish with complexity and edge cases.

Start timed mock