Problem
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Each input has exactly one solution, and you may not use the same element twice.
Example:
- Input:
nums = [2, 7, 11, 15],target = 9 - Output:
[0, 1] - Explanation:
nums[0] + nums[1] = 2 + 7 = 9
Intuition
The brute force approach checks every pair of numbers, but we can do much better. The key insight is: for each number nums[i], we need to know if target - nums[i] exists elsewhere in the array. A hash map lets us answer that question in O(1).
Approach 1 โ Brute Force
Check every pair (i, j) where i < j. If they sum to target, return the indices.
Steps:
- For each index
i, scan every indexjto the right of it - If
nums[i] + nums[j] == target, return[i, j]
1def twoSum(nums, target):
2 for i in range(len(nums)):
3 for j in range(i + 1, len(nums)):
4 if nums[i] + nums[j] == target:
5 return [i, j]- Time: O(nยฒ) โ two nested loops over n elements
- Space: O(1)
Approach 2 โ Hash Map (Optimal)
Do a single pass. For each number, check if its complement (target - num) is already in a hash map. If yes, we're done. If no, store the current number and its index.
Steps:
- Create an empty hash map (
value โ index) - For each number, compute
complement = target - num - If
complementis in the map, return[map[complement], current_index] - Otherwise, store
num โ current_indexin the map
1def twoSum(nums, target):
2 seen = {} # maps value -> index
3 for i, num in enumerate(nums):
4 complement = target - num
5 if complement in seen:
6 # complement was stored in a previous iteration, so indices are distinct
7 return [seen[complement], i]
8 seen[num] = i- Time: O(n) โ single pass, each hash map lookup is O(1)
- Space: O(n) โ hash map stores up to n entries
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| Brute Force | O(nยฒ) | O(1) | Never in production; good as a baseline answer in an interview |
| Hash Map | O(n) | O(n) | Always โ this is the standard solution |
Common Mistakes
- Using the same element twice: The hash map approach avoids this naturally โ we only look up values stored in previous iterations, so index
iis never in the map when we check for its complement. - Returning values instead of indices: The problem asks for indices, not the numbers themselves.
- Storing before checking: If you
seen[num] = ibefore checking for the complement, a number could match itself (e.g.,target = 6,num = 3would find index of 3 in the map immediately). Always check first, then store.
Related Problems
3sumโ extends two-sum to three numbers; sort + two pointerstwo-sum-ii-input-array-is-sortedโ sorted input allows two-pointer instead of hash map4sumโ two nested loops reduce it to two-sumcontains-duplicateโ same hash set patterntop-k-frequent-elementsโ hash map for counting frequencies