Code Lab

Timer: 15 min, like in an interview. Hints and autocomplete are off while it runs

Two sum

HardMap and Set15 min

Write a function twoSum(numbers, target) that finds two different items of the array numbers that add up to target, and returns their indexes as [i, j] with i < j. If there is no such pair, return null.

  • numbers holds integers, also negative ones and 0. The same value can appear more than once.
  • At most one pair adds up to target, so the answer is never ambiguous.
  • "Two different items" means two different indexes: in [3, 2, 4] with target 6 the answer is [1, 2], not [0, 0]. Two equal values at different indexes are fine: [3, 3] with target 6 gives [0, 1].
  • The array can have 200 000 items. Your code must finish in time.

Examples

twoSum([2, 7, 11, 15], 9)

Returns [ 0, 1 ]

twoSum([3, 2, 4], 6)

Returns [ 1, 2 ]

twoSum([1, 2], 10)

Returns null

Source

Loading the editor...
  1. InputtwoSum([ 2, 7, 11, 15 ], 9)
    Expected[ 0, 1 ]
  2. InputtwoSum([ 3, 2, 4 ], 6)
    Expected[ 1, 2 ]
  3. InputtwoSum([ 1, 2 ], 10)
    Expectednull

Hidden tests run on Submit