Lesson 13/25 ยท ๐๏ธ Hash Maps & Sets
๐๏ธ Hash Maps & SetsLesson 13/25
Phase 4 ยท Hash Maps & Sets20 min
Hash Maps
O(1) lookups that power everything from databases to frequency counting
A hash map (dict in Python) stores key-value pairs and provides O(1) average-case lookup, insert, and delete.
How it works: A hash function converts a key to an index in an array. Python's dict is a sophisticated hash map with collision handling built in.
How it works: A hash function converts a key to an index in an array. Python's dict is a sophisticated hash map with collision handling built in.
The classic: two sum with a hash mappython
def two_sum(nums, target):
"""Find two indices that sum to target. O(n) time, O(n) space."""
seen = {} # value โ index
for i, num in enumerate(nums):
complement = target - num
if complement in seen: # O(1) lookup
return [seen[complement], i]
seen[num] = i # Store for future lookups
return []
print(two_sum([2, 7, 11, 15], 9)) # โ [0, 1]Nested loops: O(nยฒ)โ Works but messy
# O(nยฒ) brute force
def two_sum_slow(nums, target):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]Hash map: O(n)โ Pythonic
# O(n) with hash map
def two_sum_fast(nums, target):
seen = {}
for i, num in enumerate(nums):
comp = target - num
if comp in seen:
return [seen[comp], i]
seen[num] = i๐ก
Trading O(n) space for O(n) time improvement, hash maps make this trade constantly
๐คQuick Check
What is the worst-case time complexity of a hash map lookup?
Practice Exercises
0/1 solvedExercise 1 of 1medium
โฑ 00:00Group Anagrams
Group strings that are anagrams of each other.
Expected output:
Expected output:
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]solution.py
1 / 1
Solve all 1 exercise to unlock completion