Modo entrevista. Temporizador de 10 min, sin pistas y sin autocompletado
Reverse an array in place
MediaArrays10 min
Write a function reverseInPlace(arr) that reverses an array in place: the first element changes places with the last one, the second with the one before the last, and so on.
arris an array of numbers or strings. It can be empty.- Change
arritself (mutate it), do not build a new array. - Return the same array
arr, not a copy. - Do not use the built-in
reverse()ortoReversed(), also not on a copy of the array. Hidden tests replace them with functions that throw an error. - An empty array and an array of one element stay as they are.
Use two indexes: one from the start and one from the end. Swap the elements at each index pair and move the indexes toward each other.
Ejemplos
reverseInPlace([1, 2, 3, 4, 5])Devuelve [ 5, 4, 3, 2, 1 ]
reverseInPlace(['a', 'b', 'c', 'd'])Devuelve [ 'd', 'c', 'b', 'a' ]
reverseInPlace([])Devuelve []
Cargando el editor…
- Entrada
reverseInPlace([ 1, 2, 3, 4, 5 ])Esperado[ 5, 4, 3, 2, 1 ] - Entrada
reverseInPlace([ 1, 2, 3, 4 ])Esperado[ 4, 3, 2, 1 ] - Returns the same array, reversed
Las pruebas ocultas se ejecutan al enviar