Hash Map Patterns (Two Sum)
DSA · Beginner
Definition
Store seen values in a hash map so the complement of each element is found in O(1).
The most asked interview question and a reusable pattern.
Diagram
Flowchart
Example: Two Sum
nums, target = [2, 7, 11, 15], 9
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
print([seen[target - x], i]); break
seen[x] = iOutput: [0, 1]
Complexity
O(n) time · O(n) space
Key points
- Check before inserting to avoid using an element twice
- Same idea solves subarray-sum-k
Interview questions
Sorted input?
Use two pointers for O(1) extra space.