c2cedge
Data Structures & Algorithms · B — Linear Structures

Hashing & Hash Maps

A hash map trades memory for speed: it remembers what you have seen so a repeated inner scan becomes a single O(1) lookup.

Test weight: Very highTime / question: 1–3 minDifficulty: Medium

A hash map (dictionary) stores key-value pairs and supports insert and lookup in O(1) on average. It is the single most useful tool for turning an O(n²) 'compare every pair' brute force into an O(n) solution.

Remember what you have seen

As you scan once, store each element (or its count) in a hash map. Then any 'have I seen X?' or 'how many of X?' question is answered instantly, without a second loop.

Two Sum in one pass
seen = {}                       // value -> index
for i = 0 to n-1:
    need = target - A[i]
    if need in seen: return (seen[need], i)
    seen[A[i]] = i
O(n) averageO(n)
One pass; the map can hold up to n entries.
⚡ The edge
  • Whenever the brute force is 'for each element, scan the rest' (O(n²)), ask: can a hash map remember what I've already seen and make the inner scan O(1)?
  • Use a map for counts and a set when you only need membership (have I seen this before?).
Worked example
Find two numbers in [2, 7, 11, 15] that add to 9.
  1. Scan once, asking for each number what partner it needs: 9 - 2 = 7.
  2. Store 2 in the map. Next is 7; it needs 9 - 7 = 2, which is already in the map.
  3. So 2 and 7 form the pair — found in a single pass.
Worked example
Find the first non-repeating character in 'aabbcde'.
  1. First pass: count each character -> a:2, b:2, c:1, d:1, e:1.
  2. Second pass in order: a (2) repeats, b (2) repeats, c (1) does not.
  3. So 'c' is the first character with a count of one.
⚠ Watch out
  • Hash operations are O(1) average, but O(n) in the rare worst case of many collisions.
  • A hash map uses O(n) extra memory — the price for the speed-up.
  • Keys must be hashable and stable; don't use a changing object as a key.
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms