Code Lab

Modo entrevista. Temporizador de 15 min, sin pistas y sin autocompletado

Two sum

DifícilMap 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.

Ejemplos

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

Devuelve [ 0, 1 ]

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

Devuelve [ 1, 2 ]

twoSum([1, 2], 10)

Devuelve null

Fuente

Cargando el editor…
  1. EntradatwoSum([ 2, 7, 11, 15 ], 9)
    Esperado[ 0, 1 ]
  2. EntradatwoSum([ 3, 2, 4 ], 6)
    Esperado[ 1, 2 ]
  3. EntradatwoSum([ 1, 2 ], 10)
    Esperadonull

Las pruebas ocultas se ejecutan al enviar