Two Sum
Find two indices whose values add up to target. Instead of checking every pair, walk the array once and remember each value's index in a hash map; for each number you only need to ask whether its complement target - x has already appeared.
Traced input: nums = [2, 7, 11, 15], target = 9 → [0, 1]. Original problem: neetcode.io/problems/two-integer-sum
Complexity
BestO(1)
AverageO(n)
WorstO(n)
SpaceO(n)
Best case is when the first two numbers are the pair. The map can grow to n entries.
Key idea
- For each
nums[i], the only partner that works isneed = target - nums[i]. - A hash map from value to index answers "have I seen
need?" in O(1). - Check the map before inserting
nums[i], so an element never pairs with itself. - One pass is enough: when the second element of the pair arrives, the first is already in the map.
Common mistakes
- Inserting before checking lets
[3, 2, 4], target = 6return[0, 0](using 3 twice). - Sorting first loses the original indices unless you carry them along.
- The brute-force double loop is O(n²); interviewers expect the hash map version.
- Returning values instead of indices.
Solution
Java
int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (seen.containsKey(need)) {
int j = seen.get(need);
return new int[]{j, i};
}
seen.put(nums[i], i);
}
return new int[]{};
}Python
def twoSum(nums: List[int], target: int) -> List[int]:
seen = {}
for i, x in enumerate(nums):
need = target - x
if need in seen:
return [seen[need], i]
seen[x] = i
return []C++
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> seen;
for (int i = 0; i < (int)nums.size(); i++) {
int need = target - nums[i];
auto it = seen.find(need);
if (it != seen.end()) {
return {it->second, i};
}
seen[nums[i]] = i;
}
return {};
}Edge cases
Each one has its own trace in the interactive view.
| Case | Input | Answer |
|---|---|---|
| Same value used twice The first 3 is stored, then the second 3 finds it. Two different indices, same value. | nums = [3, 3], target = 6 | [0, 1] |
| Don't reuse one element When i = 0, need = 3 is not in the map yet, so 3 never pairs with itself. | nums = [3, 2, 4], target = 6 | [1, 2] |
| Negative numbers Complements can be negative; the map doesn't care about sign. | nums = [-3, 4, 3, 90], target = 0 | [0, 2] |
| Zeros 0 + 0 = 0 works because the two zeros are at different indices. | nums = [0, 4, 3, 0], target = 0 | [0, 3] |
| Pair at the very end The worst case: the whole array is scanned before the match. | nums = [1, 2, 3, 4, 5], target = 9 | [3, 4] |
| No valid pair LeetCode guarantees exactly one answer. This code returns an empty array otherwise; say so out loud in an interview. | nums = [1, 2], target = 7 | [] |