Code Lab

Reverse an array in place

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

Examples

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

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

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

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

reverseInPlace([])

Returns []

Source

Loading the editor...
  1. InputreverseInPlace([ 1, 2, 3, 4, 5 ])
    Expected[ 5, 4, 3, 2, 1 ]
  2. InputreverseInPlace([ 1, 2, 3, 4 ])
    Expected[ 4, 3, 2, 1 ]
  3. Returns the same array, reversed

Hidden tests run on Submit.