Two Sum (LeetCode 1): Solution and Explanation

Easy
Array
Hash Table

Given an array of integers and a target, return the indices of the two different elements that add up to the target. Exactly one such pair exists, and you may not use the same element twice.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force answer writes itself: try every pair (i, j) with i < j and check whether nums[i] + nums[j] == target. That is correct but costs O(n²) time, which is about 50 million additions for an array of 10,000 numbers. The question to ask is what you are really searching for when you fix one element.

Once you are standing on nums[i], the partner you need is fully determined: it must equal target - nums[i]. So the inner loop is not really a search over pairs; it is a lookup for one specific value. Lookups for a specific value are exactly what a hash map does in constant average time. If you store each number you have seen along with its index, the question "have I seen the complement before?" becomes a single dictionary check.

That leads to a one-pass algorithm. Walk through the array once. For each element, compute the complement and check the map first. If it is there, the stored index and the current index are the answer. If not, record the current number and its index, then move on. Checking before inserting is what guarantees you never pair an element with itself, and because the earlier element of the pair is always in the map by the time you reach the later one, you can never miss the answer.

Approach: One-pass hash map

  1. Create an empty dictionary prevMap that maps each value seen so far to its index.
  2. Iterate over the array with enumerate, getting index i and value n.
  3. Compute diff = target - n, the value that would complete the pair.
  4. If diff is already in prevMap, return [prevMap[diff], i].
  5. Otherwise store prevMap[n] = i and continue to the next element.
  6. If the loop finishes without a match, return an empty list (the problem guarantees this does not happen).

Step-by-step example

nums = [3, 2, 4], target = 6
  1. i = 0, n = 3: diff = 3. The map is empty, so 3 is not found even though 3 + 3 = 6. Store {3: 0}.
  2. i = 1, n = 2: diff = 4, which is not in {3: 0}. Store {3: 0, 2: 1}.
  3. i = 2, n = 4: diff = 2, which is in the map at index 1. Return [1, 2].
  4. Notice how step one avoided pairing index 0 with itself, because the lookup happens before the insert.

Code: Python, Java, C++

1class Solution:
2    def twoSum(self, nums: List[int], target: int) -> List[int]:
3        prevMap = {}  # val : index
4        for i, n in enumerate(nums):
5            diff = target - n
6            if diff in prevMap:
7                return [prevMap[diff], i]
8            prevMap[n] = i
9        return []

Time and space complexity

Time

O(n)

Each element is visited once, and each visit performs one dictionary lookup and at most one insert, both O(1) on average.

Space

O(n)

In the worst case the matching pair is at the very end, so the map ends up holding nearly every element before the answer is found.

Other approaches

Brute force over all pairs (time O(n²), space O(1))

Two nested loops check every pair i < j. It needs no extra memory and is fine for tiny inputs, but it is quadratic and too slow for the upper constraint.

Sort plus two pointers (time O(n log n), space O(n))

Sort pairs of (value, original index), then move a left and right pointer inward based on whether the sum is too small or too large. It works, but sorting dominates and you must carry original indices along, so the hash map is simpler.

Common mistakes

  • Inserting the current number into the map before checking for its complement. With nums = [3, 2, 4] and target = 6, the first 3 would find itself and return [0, 0].
  • Building the whole map first in a separate pass and then searching without checking that the found index differs from i. A two-pass version is valid only if it rejects prevMap[diff] == i.
  • Sorting the array and returning indices from the sorted copy. The problem asks for positions in the original array.
  • Worrying that duplicates overwrite earlier indices. With the check-then-insert order, a duplicate that forms the answer, like [3, 3] with target 6, is found before it overwrites anything.

Frequently asked questions

Why is Two Sum O(n) with a hash map?

Each element needs only one constant time lookup to see whether its complement was seen earlier. One pass over n elements with O(1) work each gives O(n) total.

Can Two Sum be solved without extra space?

Only by giving up the linear time. The brute force uses O(1) space but O(n²) time. Sorting in place would lose the original indices unless you store them, which brings the space back.

Does the order of the returned indices matter?

Usually not; any order is accepted. This solution naturally returns the earlier index first, since that one comes from the map.

What if the array is already sorted?

Then the two-pointer technique solves it in O(n) time and O(1) space, which is the Two Sum II variant.