Hashing & FrequencyBeginner
Two Sum Pattern
Use a hash map to find pairs that satisfy a target condition in a single pass.
Problem: Two Sum
Find two indices in [2, 7, 11, 15] such that they add up to 9.
2
7
11
15
i
Hash Map (value → index)
empty
Check arr[0] = 2, need complement 7
Looking for 9 - 2 = 7 in map. Map is empty, so add {2: 0} to map.
Complement: 7
Step 1/5
Speed:
When to Use
- Find pair with target sum (unsorted)
- Find complement
- Count pairs with difference K
Key Indicators
- Unsorted array + target
- Find pair
- Complement-based search
Complexity
Time
O(n)
Space
O(n)
Common Problems
Two Sum4Sum IICount Pairs With Difference K
Code
seen = {}
for i, num in enumerate(arr):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = iWant all 29 patterns with detailed visual walkthroughs?
The complete book includes 84 practice problems, full decision tree, and illustrated step-by-step solutions.
Book Coming Soon ($4.99)