CodePark/ problems / Two Sum
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Hash maps and sets

Two Sum

easyabout 12 minutes in an interview

You get an array of numbers nums and a number target. Two of the numbers add up to target. Find their positions and return them as [i, j] with i < j.

  • Every input has one correct pair, no more and no fewer.
  • i and j must be different positions. They may still hold the same value, as in [5, 5].
  • Numbers can be negative or zero.
  • nums can have up to 100,000 items, so checking every pair is too slow.
Input: nums = [4, 11, 6, 1], target = 7 Output: [2, 3]6 + 1 = 7
Input: nums = [5, 5, 2], target = 10 Output: [0, 1]Two different positions with the same value.
Input: nums = [-4, 8, 3, 10], target = 6 Output: [0, 3]