Two Sum

Easy

Topics
ArrayHash Table

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

You may assume exactly one solution, and you may not use the same element twice. Return the answer in any order.

Example 1

20a71b112153
The two shaded cells add to 9, so the answer is their indices [0, 1], not their values.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: nums[0] + nums[1] == 9.

Example 2

3021a42b
Input:  nums = [3,2,4], target = 6
Output: [1,2]

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • Exactly one valid answer exists.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The brute force checks every pair — for each i, scan every j after it. That is O(n²) and wasteful because we keep re-scanning numbers we have already seen.

The key realization: for a fixed number x, there is exactly one number that completes the pair — its complement target - x. So instead of searching for it, we can remember every number we have passed in a hash map and check for the complement in O(1).

Approach

  1. Create a hash map from value → index.
  2. Iterate once. For the current value x, compute need = target - x.
  3. If need is already a key in the map, we have found the two numbers — return [map[need], i].
  4. Otherwise record x → i and move on. We store after checking so an element is never paired with itself.

Walkthrough

nums = [2, 7, 11, 15], target = 9

i=0  x=2   need=7   map={}          -> 7 not seen, store 2:0
i=1  x=7   need=2   map={2:0}       -> 2 IS seen -> return [0, 1]

Complexity

  • Time — O(n): a single pass; each hash-map lookup and insert is O(1) on average.
  • Space — O(n): in the worst case the map stores nearly every element before the matching pair appears.

Common Pitfalls

  • Storing the value in the map before checking would let an element match itself.
  • Return indices, not the values themselves.

Full Solution — all languages

class Solution:
    def twoSum(self, nums, target):
        seen = {}
        for i, x in enumerate(nums):
            if target - x in seen:
                return [seen[target - x], i]
            seen[x] = i
        return []
SensAI
Beta
Tap the mic to stop voice mode