Back to problems Solve on LeetCode → Next: Reverse Linked List →

Two Sum

Hash Map Complement Lookup — One Pass

LeetCode 1 • Easy • Arrays & Hashing

Input: nums = [3, 8, 1, 5, 11, 7], target = 12  →  Output: [2, 4]  (nums[2]+nums[4] = 1+11 = 12)

TimeO(n)single pass
SpaceO(n)hash map
Checked: 0/6 Map size: 0 Lookups: 0
Current element
Complement
In hash map
Pair found
Complement
Map
{ }
Result [ ]
Ready
Press Play to watch the algorithm, or Step to advance one operation at a time.
For each element, compute complement = target − nums[x]. If the complement is already in the hash map, we found our pair.