Problem
Given an integer array nums and an integer target, return the indices of the two different positions whose values add up to the target. The problem guarantees exactly one answer.
Original: LeetCode 1: Two Sum.
Examples
Example 1
`nums = [2, 7, 11, 15], target = 9``[0, 1]`Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2
`nums = [3, 3], target = 6``[0, 1]`Two equal values at different indices are allowed. You just cannot use the same index twice.
Example 3
`nums = [-1, -2, -3, -4], target = -7``[2, 3]`Negative numbers work the same way: -3 + -4 == -7.
Constraints
2 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9- Only one valid answer exists.
Hints
Hint 1
For each number, what would its partner have to be so the two add up to
target?Hint 2
Can you remember the numbers you have already seen, and look one up in constant time?
Hint 3
Look up the complement before you store the current number, so a value never pairs with itself.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
The brute force checks every pair i < j in O(n²) time. Instead, walk the array once and keep a hash map from value to index. For each number, look up target minus that number. If it is already in the map, return both indices. If not, store the current number and continue.
Look up the complement before you insert the current value, so an element never pairs with itself. “Indices, not values” also means you should not sort the array unless you keep the original positions.
Alternative. Sort pairs of (value, index) and run two pointers from both ends. That is O(n log n) time. It is the better choice when the input is already sorted (LeetCode 167).
Complexity
- Time
- O(n)
expected, because hash map get and put are constant on average.
- Space
- O(n)
Code
def two_sum(nums: list[int], target: int) -> list[int]:
seen: dict[int, int] = {} # value -> index
for i, value in enumerate(nums):
j = seen.get(target - value)
if j is not None:
return [j, i]
seen[value] = i
return [] # unreachable when exactly one answer exists
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
print(two_sum([3, 3], 6)) # [0, 1]
print(two_sum([-1, -2, -3, -4], -7)) # [2, 3]import java.util.Arrays;
import java.util.HashMap;
public class TwoSum {
static int[] twoSum(int[] nums, int target) {
var seen = new HashMap<Integer, Integer>(); // value -> index
for (int i = 0; i < nums.length; i++) {
var j = seen.get(target - nums[i]);
if (j != null) return new int[] {j, i};
seen.put(nums[i], i);
}
return new int[0]; // unreachable when exactly one answer exists
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 9))); // [0, 1]
System.out.println(Arrays.toString(twoSum(new int[] {3, 3}, 6))); // [0, 1]
System.out.println(Arrays.toString(twoSum(new int[] {-1, -2, -3, -4}, -7))); // [2, 3]
}
}Edge cases
- Duplicate values, as in [3, 3] with target 6.
- Negative numbers.
- A complement equal to the current value: checking before inserting handles it.
Follow-ups
- Return all pairs, with or without duplicates.
- The input is already sorted: use two pointers and O(1) extra space (LeetCode 167).
- The input arrives as a stream: keep the map and answer as items come in.
Interview script
"The brute force checks every pair in O(n²). Instead, I store each value's index in a hash map, and for every element I look up target minus it. One pass, O(n) time, O(n) space. I look up before I insert so an element can't pair with itself."
Source: LeetCode 1: Two Sum Source: Java SE 17 API: HashMap
Sources (2)
- LeetCode 1: Two Sumleetcode.com
- Java SE 17 API: HashMapdocs.oracle.com