Two Sum

easyArrays & Hashing11 stepsJava · Python · C++

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.

▶ Watch the animated trace

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

Common mistakes

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.

CaseInputAnswer
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[]
Valid Anagram →