HASHING · 8 MIN
Hash Maps
A hash map turns a key into a slot number, giving near-instant lookups.
BYTE explains
- Average insert, lookup and delete are O(1).
- Collisions (two keys, same slot) are handled by chaining or probing.
- Classic trick: store what you've seen to answer 'have I seen the complement?' in one pass.
Real world: A coat-check counter: your token number takes you straight to your coat.
Code
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
print(two_sum([2, 7, 11, 15], 9))Output ›
[0, 1]Try it in the online compiler →Checkpoint quiz
Average lookup in a hash map is…