Hash usage
easy 16 minHash 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
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.
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 on average, whether the map holds ten keys or ten million.
- 1Key"apple"
- 2hash()543217 (illustrative)
- 3mod size543217 % 10 = 7
- 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? average.Membership
x in s: have I seen this before? average, against on a list.Counting
Counter(items): how many of each? One pass, .Grouping
defaultdict(list): put things that share a key together.
The toolkit
dict, set, Counter and defaultdict
| Tool | What it is | Reach for it when | Example |
|---|---|---|---|
dict | Key to value map | Lookup tables, value to index, caches | pos = {v: i for i, v in enumerate(a)} |
set | Unique keys, no values | Seen before, dedupe, set algebra | seen = set(); seen.add(x) |
Counter | dict of counts | Frequencies, top k, anagram checks | Counter(words).most_common(3) |
defaultdict | dict with a default factory | Grouping, adjacency lists, counting | groups = defaultdict(list) |
frozenset | Immutable set | A set used as a key or set member | {frozenset({1, 2}): 'edge'} |
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 same tools in other languages
| Language | Hash map | Hash set |
|---|---|---|
| Python | dict, defaultdict, Counter | set, frozenset |
| Java | HashMap, LinkedHashMap | HashSet |
| C++ | std::unordered_map | std::unordered_set |
| JavaScript | Map, plain objects | Set |
Complexity
O(1) on average, O(n) at worst
Average case
Worst case
| Operation | Python | Average | Worst |
|---|---|---|---|
| Insert or update | d[k] = v, s.add(x) | ||
| Lookup | d[k], d.get(k) | ||
| Delete | del d[k], d.pop(k), s.discard(x) | ||
| Membership | k in d, x in s | ||
| Size | len(d) | ||
| Clear, iterate, copy | d.clear(), for k in d, d.copy() | ||
| Value search | v in d.values() |
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?
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 keys.
Fast
Hashing a key of length costs ; 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)] frozensetfor 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
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'Pattern 1
Counting frequencies
The frequency counter
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])) # 2Pattern 2
Lookup by complement: Two Sum
One pass with a value-to-index map
nums = [2, 7, 11, 15], target = 9
| i | num | need = 9 − num | need in seen? | seen after |
|---|---|---|---|---|
| 0 | 2 | 7 | No | {2: 0} |
| 1 | 7 | 2 | Yes, at index 0 | return [0, 1] |
Why the map wins
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.
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')Removing duplicates
| Approach | Keeps order? | Time |
|---|---|---|
list(set(items)) | No | |
list(dict.fromkeys(items)) | Yes, first occurrence | |
sorted(set(items)) | Sorted order | |
Nested loop with in on a list | Yes |
Pattern 4
Grouping by a canonical key
Things that should end up together share a key
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)) # TrueCost for n words of length up to L
Pattern 5
Caching and memoization
A cache in front of an expensive call
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 resultsWhat the cache saves
Pattern 6
Prefix sum plus a map
Turn a range sum into a lookup
Count subarrays with sum k
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)) # 3Choosing
When a hash is the right tool
Hash map or something else?
Perfect for
- 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
| Operation | Hash map | Unsorted array | Sorted array | Balanced BST |
|---|---|---|---|---|
| Lookup | avg | |||
| Insert | avg | append | ||
| Sorted iteration | No | No | Yes | Yes |
| Range query | No | No | Yes, binary search | Yes |
| Min / max |
Recap
Key points
Key points
- A hash map computes where a key lives, so insert, lookup and delete are average and 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 lookup, turning into at the cost of 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.