Code Lab

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

Merge two sorted arrays

MediaArrays10 min

Write a function mergeArrays(a, b). Both arrays are sorted from small to large. Return a new array with all elements of a and b, also sorted from small to large.

  • a and b hold integers, also negative ones. Each one can have any length, also 0.
  • Keep repeated values: [1, 2] and [2, 3] give [1, 2, 2, 3].
  • Always return a new array, even when a or b is empty. Do not change (do not mutate) a or b.
  • Do not sort the joined array. Walk through both arrays once, like merging two sorted piles of cards. A hidden test makes sort and toSorted throw an error.

Ejemplos

mergeArrays([1, 3, 5], [2, 4])

Devuelve [ 1, 2, 3, 4, 5 ]

mergeArrays([], [7])

Devuelve [ 7 ]

mergeArrays([1, 2], [2, 3])

Devuelve [ 1, 2, 2, 3 ]

Preguntada en Mastercard · Fuente

Cargando el editor…
  1. EntradamergeArrays([ 1, 3, 5 ], [ 2, 4 ])
    Esperado[ 1, 2, 3, 4, 5 ]
  2. EntradamergeArrays([], [ 7 ])
    Esperado[ 7 ]
  3. EntradamergeArrays([ 1, 2 ], [ 2, 3 ])
    Esperado[ 1, 2, 2, 3 ]

Las pruebas ocultas se ejecutan al enviar