Hash Maps (Dictionaries)
Data Structures & Algorithms · Hash Maps & Sets · Basics · 14 min
The most useful interview tool: instant lookup by key.
A coat-check wall of numbered hooks. Every time you see a new thing, you hang a tag on its hook. Later, 'have I seen this?' is just a glance at one hook, never a search through the whole room.
The idea in everyday words
A hash map is a coat-check counter. You hand over your coat (the value) with a name tag you choose (the key). Later you say the name and get your coat back instantly: the attendant knows exactly which hook it is on and never searches through every coat.
What it does
Stores key → value pairs. Lookup, insert and delete are O(1) on average.
ages = {"ana": 25, "bo": 31}
ages["ana"] # 25, instantly
A hash function turns the key into a locker number. That's why it's fast.
Classic: Two Sum
Find two numbers that add up to a target. Instead of checking every pair (O(n²)), remember what you've seen:
For each number x, the partner you need is target - x. Is the partner already in the map? Done!
nums = [2, 7, 11], target = 9 → see 2 (need 7, not seen) → see 7 (need 2, seen at index 0) → answer [0, 1].
Step by step
- seen = {}:
Empty map. target = 9.
- x = 2 (i=0):
Need 9-2 = 7. Not in map. Save seen[2] = 0.
- x = 7 (i=1):
Need 9-7 = 2. 2 IS in map at index 0!
- Answer:
Return [0, 1]. Only one pass → O(n).
Code example
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
need = target - x
if need in seen:
return [seen[need], i]
seen[x] = i
return []
print(two_sum([2, 7, 11, 15], 9))Complexity
- Time: O(n)
- Space: O(n)
Interview tips
Two Sum is the #1 most asked interview question. Know it cold.
Mention worst case O(n) per lookup due to collisions (rare).
Counting frequencies (anagrams, top-k) uses maps.
Challenge: Count Each Letter
Return a dictionary/object counting how many times each character appears.
Example: count_chars("abca") → {"a": 2, "b": 1, "c": 1}
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Two Sum (Easy)
- Valid Anagram (Easy)
- First Unique Character in a String (Easy)
- Group Anagrams (Medium)
More in Hash Maps & Sets
Previous: Deques & Monotonic Stacks · Next: Inside a Hash Table