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.
numbersholds integers, also negative ones and0. 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 target6the answer is[1, 2], not[0, 0]. Two equal values at different indexes are fine:[3, 3]with target6gives[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
Loading the editor...
- Input
twoSum([ 2, 7, 11, 15 ], 9)Expected[ 0, 1 ] - Input
twoSum([ 3, 2, 4 ], 6)Expected[ 1, 2 ] - Input
twoSum([ 1, 2 ], 10)Expectednull
Hidden tests run on Submit