Code Lab

Modo entrevista. Cronômetro de 10 min, sem dicas e sem autocompletar

Reverse an array in place

MédiaArrays10 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.

  • arr is an array of numbers or strings. It can be empty.
  • Change arr itself (mutate it), do not build a new array.
  • Return the same array arr, not a copy.
  • Do not use the built-in reverse() or toReversed(), 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.

Exemplos

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

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

reverseInPlace(['a', 'b', 'c', 'd'])

Retorna [ 'd', 'c', 'b', 'a' ]

reverseInPlace([])

Retorna []

Fonte

Carregando o editor...
  1. EntradareverseInPlace([ 1, 2, 3, 4, 5 ])
    Esperado[ 5, 4, 3, 2, 1 ]
  2. EntradareverseInPlace([ 1, 2, 3, 4 ])
    Esperado[ 4, 3, 2, 1 ]
  3. Returns the same array, reversed

Os testes ocultos rodam no envio