Two Sum

Pattern: Hashing and frequency

easy

Find the two indexes whose values add up to the target in one pass, by looking up each value's needed partner in a map of earlier values.

The problem

You are given an array nums and a target. Exactly one pair of different positions has values that add up to the target. Return those two indexes. For example, in [2, 7, 11, 15] with target 9, the answer is [0, 1], because 2 + 7 = 9. You may not use the same element twice.

The function name twoSum matches LeetCode. Use the link above for the exact statement. This guide returns the smaller index first.

Think first

  • For a value x, what exact value must its partner have?
  • Checking every pair works. How many pairs are there for 10,000 numbers?
  • As you walk the array, what could you remember so that finding the partner takes one step?

Hints

    Brute force, and why it fails

    Check every pair (i, j) with i < j. That is about n²/2 pairs: 50 million for 10,000 numbers. It works, but a hash map does it in one pass. Sorting with two pointers is O(n log n), but sorting loses the original indexes unless you carry them along.

    The key insight

    Each value knows exactly which partner it needs. A map of the values seen so far turns "search for the partner" into one look-up, so one pass finds the pair.

    Dry run

    20 
    71 
    112 
    153 
    target9
    indexOf{}

    nums = [2, 7, 11, 15] and target = 9. The map will remember each value we pass and its index. It starts empty.

    Step 1 of 3

    The plan

    indexOf = empty map
    for i from 0 to n - 1:
        need = target - nums[i]
        if need is in indexOf:
            return [indexOf[need], i]
        indexOf[nums[i]] = i
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    One pass with average O(1) map operations. The map can hold up to n values.

    Edge cases

    • Two equal values, as in [3, 3] with target 6: the second 3 finds the first, because we look up before recording.
    • Negative values and zero work the same way.
    • Values near ±10⁹: target - x stays within 32 bits for LeetCode's limits.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer, Integer> indexOf = new HashMap<>();   // value -> an index where we saw it
            for (int i = 0; i < nums.length; i++) {
                int need = target - nums[i];
                if (indexOf.containsKey(need)) {
                    return new int[]{indexOf.get(need), i};
                }
                indexOf.put(nums[i], i);
            }
            return new int[0];                                 // not reached: an answer always exists
        }
    }

    C++

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int, int> indexOf;                   // value -> an index where we saw it
            for (int i = 0; i < static_cast<int>(nums.size()); i++) {
                int need = target - nums[i];
                auto found = indexOf.find(need);
                if (found != indexOf.end()) {
                    return {found->second, i};
                }
                indexOf[nums[i]] = i;
            }
            return {};                                         // not reached: an answer always exists
        }
    };

    Python

    class Solution:
        def twoSum(self, nums: list[int], target: int) -> list[int]:
            index_of = {}                           # value -> an index where we saw it
            for i, x in enumerate(nums):
                need = target - x
                if need in index_of:
                    return [index_of[need], i]
                index_of[x] = i
            return []                               # not reached: an answer always exists

    Common mistakes

    • Recording nums[i] before looking up, which pairs a value with itself (target 6, value 3).
    • Returning the values instead of the indexes.
    • Sorting first and then returning indexes of the sorted array.

    Similar problems