Two Sum

EasyArrays and hashing

You are given an array of integers nums and an integer target. Exactly one pair of numbers in nums adds up to target.

Return the indexes of those two numbers, in either order. The two indexes must be different, though the numbers at them can be equal.

Examples

Example 1
Input:  nums = [4, 9, 1, 6], target = 7
Output: [2, 3]

nums[2] + nums[3] is 1 + 6 = 7.

Example 2
Input:  nums = [5, 5, 11], target = 10
Output: [0, 1]

The same value, at two different indexes.

Constraints

  • 2 ≤ nums.length ≤ 10⁴
  • -10⁹ ≤ nums[i], target ≤ 10⁹
  • Exactly one pair works.

Stuck?

Hint 1

For each number, the partner you need is target - number. How quickly can you tell whether you have already passed it?

Hint 2

Keep a Map from each value to its index as you go. One pass is enough.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur