Two Sum

easy

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

You may assume each input has exactly one solution, and you may not use the same element twice. You can return the two indices in any order.

Hints

You're really searching for a partner for each number — given one value, what single other value would complete the sum?
For value x, the partner you need is exactly target - x. If you've already met that partner, you're done.
Store every value you've seen in a hash map (value → index) so the partner lookup is O(1) instead of a scan.

Common doubts

The indices. For nums = [2,7,11,15], target = 9 the answer is [0,1], not [2,7].
No — the answer may be returned in any order. Our judge sorts the pair, so [0,1] and [1,0] both pass.
No. That's why the hash-map solution checks for the complement before inserting the current element — it prevents pairing an index with itself.

Interview follow-ups

Yes — the one-pass hash map is O(n) time, O(n) space, by looking up each element's complement target - x as you go.
Use two pointers from both ends: move them inward based on whether the current sum is too small or too large — O(n) time and O(1) extra space. This is the gateway to 3Sum.

Fun facts

  • Two Sum is many people's very first coding-interview problem — the classic warm-up that introduces the hash-map complement trick.
  • The complement trick generalises: 3Sum fixes one number and runs Two Sum on the rest, and subarray-sum-equals-k stores prefix sums in the very same 'have I seen the complement?' style.

Asked at

AmazonGoogleAppleMicrosoftBloombergAdobe
Frequently Sometimes Occasionally
Example 1
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2
Input: nums = [3,2,4], target = 6
Output: [1,2]
nums[1] + nums[2] == 6.
Example 3
Input: nums = [3,3], target = 6
Output: [0,1]
The two 3s live at indices 0 and 1.
Constraints

- 2 <= nums.length <= 10^4 - -10^9 <= nums[i] <= 10^9 - -10^9 <= target <= 10^9 - Only one valid answer exists.

Solve this problem →