Drill

ProblemsJavaScript › patterns

Reverse a list end to end

easypatternsTwo pointersArraysJavaScript

A replay view shows the most recent reading first, so the buffer has to come back the other way round.

reverseReadings(readings: list<int>) → list<int>

Solve it in the editor →

Where you start

function reverseReadings(readings) {
  
}

Worked examples

CallResult
reverseReadings([1,2,3])[3,2,1]
reverseReadings([1,2,3,4])[4,3,2,1]
reverseReadings([7])[7]
reverseReadings([])[]

Hint

Put one index at each end. Swap what they point at, then step them towards each other until they meet.

Reference solution in JavaScript
function reverseReadings(readings) {
  const out = readings.slice();
  let i = 0;
  let j = out.length - 1;
  while (i < j) {
    const swap = out[i];
    out[i] = out[j];
    out[j] = swap;
    i += 1;
    j -= 1;
  }
  return out;
}

The same problem in another language

More patterns problems in JavaScript