Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
- 2 <= nums.length <= 10⁴
- -10⁹ <= nums[i] <= 10⁹
- -10⁹ <= target <= 10⁹
- Exactly one valid answer exists
nums = [2,7,11,15], target = 9[0,1]nums = [3,2,4], target = 6[1,2]nums = [3,3], target = 6[0,1]Finding a pair of numbers that adds up to a specific target is a classic search problem. The goal is to identify the indices of two distinct elements that, when combined, satisfy the target sum requirement.
The most straightforward approach is to check every possible pair of numbers. We use one loop to pick the first number and a second loop to scan the rest of the array for a partner.
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]The O(N²) approach is slow because we perform a full linear scan just to find one specific value (the complement). The core insight is that if we know our current value is x, we are looking for exactly one specific partner: target - x.
Instead of scanning for the partner, we can "remember" every number we've already seen. We use a Hash Map to store values as keys and their indices as values. As we walk through the array, we check if the current number's "required partner" is already in our memory.
seen = {}
for i, x in enumerate(nums):
partner = target - x
if partner in seen:
return [seen[partner], i]
seen[x] = iOne-Pass Hash Map
Checking for complement while iterating
Key Insight
We can iterate through the array once. For each element, we calculate the complement (Target - Current). If this complement is already in our hash map, we found the pair!
Time & Space
Time: O(N) because we traverse once. Space: O(N) because the hash map stores up to N elements.