← BACK TO KNOWLEDGE
KNOWLEDGE
Two Sum: One-Pass Hash Table Pattern
— views— comments
How to convert an O(n²) pairwise search into an O(n) linear scan by dynamically storing previously visited complements in a hash map.
INTERACTIVE ALGORITHM WORKBENCH
Two Sum Visualizer
EasyArrays & Hash TableTime O(n)Space O(n)
Array
| Index | 0 | 1 | 2 | 3 |
| Value | 2 | 7 | 11 | 15 |
Hash Map (value → index)
| Value | Index |
|---|---|
We've seen 0 numbers so far.
Target9
Current2 (index 0)
Complement7
Lookup StatusReady
1def two_sum(nums, target):▶2 seen = {}3 for i, num in enumerate(nums):4 complement = target - num5 if complement in seen:6 return [seen[complement], i]7 seen[num] = i8 return []WHY THIS STEP WORKS
Initialize an empty hash map (seen = {}). As we iterate through the array, we check if the complement already exists before storing the current number.
- 1Target sum is 9
- 2Initialize seen = {}
- 3Begin array iteration at index 0
Comments