Two Sum

Easy#1find a pair

You get an array of numbers and a target sum. Find two different elements that add up to the target and return their indices. There is exactly one such pair. Our example: [5, 1, 8, 6, 5, 3] with the sum 10 — the answer is [0, 4], the two fives.

input
nums: an array of integers; target: an integer.
returns
The indices of the two numbers, [i, j]: two different indices with nums[i] + nums[j] == target, in any order.
constraints
  • 2 ≤ nums.length ≤ 1000
  • −10⁹ ≤ nums[i] ≤ 10⁹
  • −2·10⁹ ≤ target ≤ 2·10⁹
  • exactly one pair adds up to target
our 8 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
function twoSum(nums, target) {

}
Ctrl ↵
format
reset

saved in this browser

8 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more hash map problems

Pattern “Hash map” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.