Skip to the page

Foundations · core

Hash maps and sets

A hash map or hash set turns 'have I seen this?' and 'how many of these?' into O(1) average lookups, which is the move behind two-sum, grouping, counting and removing duplicates.

The notes

What you must know

  • Patterns: complement lookup (two-sum: is target - x already seen?), counting (frequency map), grouping (key to list), dedupe (set), first unique (count, then scan).
  • Counting in each language: Java map.merge(k, 1, Integer::sum) or getOrDefault(k, 0) + 1; Python collections.Counter or dict.get(k, 0) + 1; C++ ++m[k] (a missing key starts at 0).
  • Keys need value equality and a matching hash: Python tuples work as keys and lists do not; in Java a List<Integer> or a record works by value but an int[] compares by reference; in C++ unordered_map has no hash for std::pair, so use std::map, a custom hash, or encode r * cols + c.
  • Composite keys built as strings need a separator: without one, (1, 23) and (12, 3) both become '123'.
  • Iteration order: Java HashMap and C++ unordered_map give no order guarantee; Python dict keeps insertion order. Use LinkedHashMap or TreeMap in Java and std::map in C++ when the order matters.
  • Average O(1) per operation; total O(n) time and O(n) extra space. Say the space cost out loud.
  • Group anagrams: the key is the word with its letters sorted, or a 26-count tuple or string; the count key makes each word O(L) instead of O(L log L).

The red pen

Common traps: mistake → fix

  • Mistake: A hash map lookup is always O(1)

    Fix: it is O(1) on average; a bad hash can make it O(n).

  • Mistake: A set of int arrays (Java) removes duplicate pairs

    Fix: arrays compare by reference; use a list, a string or a tuple as the key.

  • Mistake: Two-sum with a map built first can pair an element with itself

    Fix: check seen-before while scanning, or check counts.

  • Mistake: Iterating a hash map gives the insertion order

    Fix: true only in Python (and LinkedHashMap).

Easy to hard

Questions interviewers ask, easy to hard

  1. Two sum: return the indices. Why is a hash map better than a nested loop?
  2. Return every pair, including duplicates. What changes?
  3. Group anagrams. What key do you use, and what is the complexity?
  4. How do you use a pair (row, column) as a key in Java, Python and C++?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview