AlgoViz

Hash usage

easy 16 min

Hash maps and hash sets find a key by computing where it lives instead of searching for it, so insert, lookup and delete cost O(1) on average.

Video lesson · Chapter 1 of 7

The same request again

0:00 / 6:22

Using hash tables — The ten-kilo icebox

1:27Reel

Read caption

Lio finds a pair totaling ten kilograms by looking up the missing weight and retaining earlier crate indices. Ask for the missing weight before storing this crate.

How it works

Step through the idea, or press Play.

Step 1 of 3

Spot the question. Have I seen x? How many x? Where is x? Which group does x belong to? Each is a lookup by key

Understand it

Start here

Compute the location, do not search for it

Think of a library with numbered shelves. Instead of checking every book, you apply a formula to the title that tells you exactly which shelf to walk to. A hash map does the same with keys: a hash function turns the key into a number, the number becomes a slot index, and the value is stored or read at that slot. Because the location is computed, a lookup costs O(1)O(1) on average, whether the map holds ten keys or ten million.

From key to slot
  1. 1Key"apple"
  2. 2hash()543217 (illustrative)
  3. 3mod size543217 % 10 = 7
  4. 4Slot 7store or read here

Python does all of this inside dict and set. How hash functions, collisions and resizing work is covered in [hash implementation](/learn/dsa/hash-implementation); this page is about using them well.

  • Lookup by key

    d[k], d.get(k): what goes with this key? O(1)O(1) average.

  • Membership

    x in s: have I seen this before? O(1)O(1) average, against O(n)O(n) on a list.

  • Counting

    Counter(items): how many of each? One pass, O(n)O(n).

  • Grouping

    defaultdict(list): put things that share a key together.

The toolkit

dict, set, Counter and defaultdict

ToolWhat it isReach for it whenExample
dictKey to value mapLookup tables, value to index, cachespos = {v: i for i, v in enumerate(a)}
setUnique keys, no valuesSeen before, dedupe, set algebraseen = set(); seen.add(x)
Counterdict of countsFrequencies, top k, anagram checksCounter(words).most_common(3)
defaultdictdict with a default factoryGrouping, adjacency lists, countinggroups = defaultdict(list)
frozensetImmutable setA set used as a key or set member{frozenset({1, 2}): 'edge'}
Python
from collections import Counter, defaultdictstock = {"apple": 5, "banana": 3}stock["cherry"] = 8                 # insertstock["apple"] = 6                  # same key: value replacedprint(stock.get("kiwi", 0), "banana" in stock)   # 0 Trueseen = set()for x in [3, 1, 3]:    if x in seen:        print("repeat:", x)         # repeat: 3    seen.add(x)c = Counter("mississippi")print(c.most_common(2))             # [('i', 4), ('s', 4)]groups = defaultdict(list)for w in ["eat", "tea", "tan"]:    groups["".join(sorted(w))].append(w)print(dict(groups))                 # {'aet': ['eat', 'tea'], 'ant': ['tan']}
The four tools side by side. Every operation shown is O(1) average except building and printing.
Edit and run it in your browser

The same tools in other languages

LanguageHash mapHash set
Pythondict, defaultdict, Counterset, frozenset
JavaHashMap, LinkedHashMapHashSet
C++std::unordered_mapstd::unordered_set
JavaScriptMap, plain objectsSet

Complexity

O(1) on average, O(n) at worst

Average case

α=nm,E[cost of insert, lookup, delete]=O(1+α)=O(1)\alpha = \frac{n}{m}, \qquad \mathbb{E}[\text{cost of insert, lookup, delete}] = O(1 + \alpha) = O(1)
nn keys spread over mm slots. The table grows whenever the load factor α\alpha passes a threshold (about 23\tfrac{2}{3} in CPython, 0.75 in Java), so α\alpha stays bounded and the expected cost is constant. Each resize is O(n)O(n), but rare enough to be O(1)O(1) amortized per insert.

Worst case

all n keys share one slot  ⟹  Tlookup(n)=O(n)\text{all } n \text{ keys share one slot} \;\Longrightarrow\; T_{\text{lookup}}(n) = O(n)
A bad hash function or adversarial input can pile keys into one place, and a lookup then compares against every one of them. Python randomises string hashes per process to make this hard to trigger on purpose.
OperationPythonAverageWorst
Insert or updated[k] = v, s.add(x)O(1)O(1)O(n)O(n)
Lookupd[k], d.get(k)O(1)O(1)O(n)O(n)
Deletedel d[k], d.pop(k), s.discard(x)O(1)O(1)O(n)O(n)
Membershipk in d, x in sO(1)O(1)O(n)O(n)
Sizelen(d)O(1)O(1)O(1)O(1)
Clear, iterate, copyd.clear(), for k in d, d.copy()O(n)O(n)O(n)O(n)
Value searchv in d.values()O(n)O(n)O(n)O(n)
Space is O(n)O(n) for nn stored entries, plus some spare slots. len is a stored counter, not a walk.

Keys

What can be a key: hashable and immutable

Can I use this as a dict key or set member?

A key must keep the same hash for as long as it sits in the map. Mutable containers could change after insertion, so Python refuses them.

What a good hash gives you

  • Deterministic

    The same key always gives the same hash. That is exactly why keys must not change.

  • Uniform

    Keys spread evenly over the slots, so each slot holds about α\alpha keys.

  • Fast

    Hashing a key of length kk costs O(k)O(k); Python caches a string's hash after the first time.

  • Avalanche

    A tiny change to the key (cat vs cot) gives a completely different hash.

Good keys

  • Numbers and strings: d[42], d['ann']
  • Tuples of immutables: grid[(r, c)]
  • frozenset for an unordered group
  • A canonical string: ''.join(sorted(word))

Bad keys

  • A list: d[[1, 2]] raises TypeError
  • A dict or set as a key
  • An object you mutate after inserting it
  • Floats from arithmetic: 0.1 + 0.2 != 0.3
Python
visited = set()visited.add((2, 3))                  # grid cell (row, col)print((2, 3) in visited)             # Trueedges = {frozenset({"a", "b"}): 5}   # undirected edge a-bprint(edges[frozenset({"b", "a"})])  # 5: same key either waytry:    {}[[1, 2]] = "x"except TypeError as e:    print(e)                         # unhashable type: 'list'
Composite keys: a tuple for an ordered pair, a frozenset when order should not matter.
Edit and run it in your browser

Pattern 1

Counting frequencies

The frequency counter

Six items apple, banana, apple, cherry, banana, apple give {apple: 3, banana: 2, cherry: 1} in six O(1) updates. Step through it in the visualizer.
Python
from collections import Counterdef first_unique(s):    freq = Counter(s)                # pass 1: count    for i, ch in enumerate(s):       # pass 2: first count of 1        if freq[ch] == 1:            return i    return -1def is_anagram(a, b):    return Counter(a) == Counter(b)  # same letters, same countsdef majority(nums):    value, times = Counter(nums).most_common(1)[0]    return value if times > len(nums) // 2 else Noneprint(first_unique("swiss"))         # 1 ('w')print(is_anagram("listen", "silent"))  # Trueprint(majority([2, 2, 1, 2, 3]))     # 2
Three classic questions answered by one counter.
Edit and run it in your browser

Pattern 2

Lookup by complement: Two Sum

One pass with a value-to-index map

Check first, then store, so a number never pairs with itself.

nums = [2, 7, 11, 15], target = 9

inumneed = 9 − numneed in seen?seen after
027No{2: 0}
172Yes, at index 0return [0, 1]
Found in two steps. The visualizer runs a trickier case, [3, 2, 4] with target 6, where storing before checking would wrongly pair 3 with itself.

Why the map wins

(n2)=n(n−1)2⏟brute force: every pair=O(n2)vsn×O(1)⏟one lookup per element=O(n)\underbrace{\binom{n}{2} = \frac{n(n-1)}{2}}_{\text{brute force: every pair}} = O(n^2) \qquad \text{vs} \qquad \underbrace{n \times O(1)}_{\text{one lookup per element}} = O(n)
For n=10,000n = 10{,}000 that is about 50 million pair checks against 10,000 lookups. The price is O(n)O(n) extra space for the map.

Pattern 3

Seen sets and deduplication

A set answers one question very fast: have I met this before? That covers duplicate detection, visited nodes in a graph search, cycle detection, and keeping only the first copy of each item.

Python
def has_duplicate(nums):    seen = set()    for x in nums:        if x in seen:            return True        seen.add(x)    return Falsedef dedupe_keep_order(items):    return list(dict.fromkeys(items))   # dict keeps first-seen orderdef longest_unique_run(s):    last, start, best = {}, 0, 0        # char -> last index    for i, ch in enumerate(s):        if ch in last and last[ch] >= start:            start = last[ch] + 1        # jump past the repeat        last[ch] = i        best = max(best, i - start + 1)    return bestprint(has_duplicate([3, 1, 4, 1, 5]))   # Trueprint(dedupe_keep_order([3, 1, 3, 2, 1]))  # [3, 1, 2]print(longest_unique_run("abcabcbb"))   # 3 ('abc')
Seen-set patterns, including the sliding-window version that tracks the last index of each character.
Edit and run it in your browser

Removing duplicates

ApproachKeeps order?Time
list(set(items))NoO(n)O(n)
list(dict.fromkeys(items))Yes, first occurrenceO(n)O(n)
sorted(set(items))Sorted orderO(nlog⁡n)O(n \log n)
Nested loop with in on a listYesO(n2)O(n^2)

Pattern 4

Grouping by a canonical key

Things that should end up together share a key

defaultdict(list) does the "no" branch for you. cat, act and tac all sort to "act"; dog and god sort to "dgo".
Python
from collections import defaultdictdef group_sorted(words):    groups = defaultdict(list)    for w in words:        groups["".join(sorted(w))].append(w)    # O(L log L) per word    return list(groups.values())def group_counts(words):    groups = defaultdict(list)    for w in words:        counts = [0] * 26        for ch in w:            counts[ord(ch) - ord("a")] += 1        groups[tuple(counts)].append(w)         # O(L) per word    return list(groups.values())words = ["cat", "dog", "act", "god", "tac", "eat"]print(group_sorted(words))   # [['cat', 'act', 'tac'], ['dog', 'god'], ['eat']]print(group_counts(words) == group_sorted(words))   # True
Two choices of key for anagrams: sorted letters, or a tuple of 26 letter counts.
Edit and run it in your browser

Cost for n words of length up to L

Tsorted key=O(n⋅Llog⁡L)Tcount key=O(n⋅L)S=O(n⋅L)T_{\text{sorted key}} = O(n \cdot L \log L) \qquad T_{\text{count key}} = O(n \cdot L) \qquad S = O(n \cdot L)
The dict work is O(1)O(1) average per word; building the key dominates. The count key wins for long words, the sorted key is simpler to write.

Pattern 5

Caching and memoization

A cache in front of an expensive call

The Web cache scene in the visualizer runs this with URLs: six requests, three hits, three misses.
Python
from functools import lru_cachememo = {}def fib(n):    if n < 2:        return n    if n in memo:                    # hit: no recursion        return memo[n]    memo[n] = fib(n - 1) + fib(n - 2)    return memo[n]@lru_cache(maxsize=None)             # arguments must be hashabledef fib2(n):    return n if n < 2 else fib2(n - 1) + fib2(n - 2)print(fib(30), fib2(30))             # 832040 832040print(fib2.cache_info().currsize)    # 31 cached results
A hand-written memo dict and the standard-library decorator do the same thing.
Edit and run it in your browser

What the cache saves

C(n)=C(n−1)+C(n−2)+1  ⇒  C(n)=2Fn+1−1=O(φn)vsn+1 distinct calls with a memoC(n) = C(n-1) + C(n-2) + 1 \;\Rightarrow\; C(n) = 2F_{n+1} - 1 = O(\varphi^n) \qquad \text{vs} \qquad n + 1 \text{ distinct calls with a memo}
Plain recursive fib(30) makes 2,692,537 calls; with the memo only 31 values are ever computed. φ≈1.618\varphi \approx 1.618 is the golden ratio.

Pattern 6

Prefix sum plus a map

Turn a range sum into a lookup

P0=0,  Pj+1=Pj+aj∑t=ijat=Pj+1−Pi=k    ⟺    Pi=Pj+1−kP_0 = 0,\; P_{j+1} = P_j + a_j \qquad \sum_{t=i}^{j} a_t = P_{j+1} - P_i = k \;\iff\; P_i = P_{j+1} - k
At each position, the number of subarrays ending here with sum kk equals the number of earlier prefix sums equal to the current prefix minus kk. A dict of prefix-sum counts answers that in O(1)O(1) average.

Count subarrays with sum k

Look up before you record the current prefix, for the same reason Two Sum checks before it stores.
Python
def subarray_sum(nums, k):    seen = {0: 1}                    # empty prefix, seen once    prefix = count = 0    for x in nums:        prefix += x        count += seen.get(prefix - k, 0)        seen[prefix] = seen.get(prefix, 0) + 1    return countprint(subarray_sum([3, 4, 7, 2, -3, 1, 4, 2], 7))   # 4print(subarray_sum([1, 1, 1], 2))                   # 2print(subarray_sum([1, -1, 0], 0))                  # 3
The visualizer steps through this exact input: four subarrays sum to 7.
Edit and run it in your browser

Choosing

When a hash is the right tool

Hash map or something else?

Most of the time you fall through to the last box.

Perfect for

  • O(1)O(1) lookup by key and frequency counting
  • Two Sum and other complement searches
  • Finding duplicates or the first unique item
  • Grouping anagrams, categorising items
  • Caching and memoization
  • Subarray sums with prefix sum plus a map

Consider alternatives when

  • You need sorted order: a TreeMap or balanced BST
  • You need range queries: a segment tree or sorted array
  • Memory is tight: two pointers on sorted input
  • Keys are small integers: a plain array
  • You need the min or max fast: a heap
OperationHash mapUnsorted arraySorted arrayBalanced BST
LookupO(1)O(1) avgO(n)O(n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)
InsertO(1)O(1) avgO(1)O(1) appendO(n)O(n)O(log⁡n)O(\log n)
Sorted iterationNoNoYesYes
Range queryNoNoYes, binary searchYes
Min / maxO(n)O(n)O(n)O(n)O(1)O(1)O(log⁡n)O(\log n)

Recap

Key points

Key points

  • A hash map computes where a key lives, so insert, lookup and delete are O(1)O(1) average and O(n)O(n) worst case.
  • Python's tools: dict, set, Counter, defaultdict, frozenset; {} is a dict, set() is an empty set.
  • Keys must be hashable and must not change: use tuples and frozensets, never lists.
  • Six patterns: count, complement lookup, seen set, group by canonical key, cache, prefix sum plus map.
  • Each pattern swaps an inner search loop for an O(1)O(1) lookup, turning O(n2)O(n^2) into O(n)O(n) at the cost of O(n)O(n) space.
  • Check before you store (Two Sum, prefix sums) so an element never matches itself.
  • Use something else when you need order, ranges, min or max, or when keys are small integers.

Sources