Code Lab

Mode entretien. Minuteur de 10 min, sans indices ni autocomplétion

Reverse an array in place

MoyenArrays10 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.

Exemples

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

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

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

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

reverseInPlace([])

Renvoie []

Source

Chargement de l'éditeur...
  1. EntréereverseInPlace([ 1, 2, 3, 4, 5 ])
    Attendu[ 5, 4, 3, 2, 1 ]
  2. EntréereverseInPlace([ 1, 2, 3, 4 ])
    Attendu[ 4, 3, 2, 1 ]
  3. Returns the same array, reversed

Les tests cachés se lancent à la soumission