Skip to content
EasyThe Algebra of Membershiparrayhash-map

Two Sum

Problem statement

Statement

Given an array of integers nums and a target integer target, return the indices of the two numbers in the array that add up to target. You may assume exactly one solution exists, and you may not use the same element twice. The answer can be returned in any order.

Examples

nums   = [2, 7, 11, 15]
target = 9
→ [0, 1]   because nums[0] + nums[1] == 9

nums   = [3, 2, 4]
target = 6
→ [1, 2]

nums   = [3, 3]
target = 6
→ [0, 1]

Constraints

  • 2 ≤ len(nums) ≤ 10^4
  • -10^9 ≤ nums[i] ≤ 10^9
  • -10^9 ≤ target ≤ 10^9
  • Exactly one valid pair exists.

What the problem is really testing

Two Sum is not about arithmetic; it is about recognising the seen-so-far pattern. The O(n²) brute-force solution is obvious; the O(n) solution requires you to reframe the question from "is there a pair?" to "has the complement of the current element already passed by?" That reframe is the single most useful habit in array problems.

O(n)

Time

O(n)

Extra space