Drill

ProblemsJava › patterns

Reverse a list end to end

easypatternsTwo pointersArraysJava

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>

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

List<Integer> reverseReadings(List<Integer> readings) {
    
}

Worked examples

CallResult
reverseReadings(Main.<Integer>ls(1, 2, 3))Main.<Integer>ls(3, 2, 1)
reverseReadings(Main.<Integer>ls(1, 2, 3, 4))Main.<Integer>ls(4, 3, 2, 1)
reverseReadings(Main.<Integer>ls(7))Main.<Integer>ls(7)
reverseReadings(Main.<Integer>ls())Main.<Integer>ls()

Hint

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

Reference solution in Java
List<Integer> reverseReadings(List<Integer> readings) {
    List<Integer> out = new ArrayList<>(readings);
    int i = 0, j = out.size() - 1;
    while (i < j) {
        int swap = out.get(i);
        out.set(i, out.get(j));
        out.set(j, swap);
        i++;
        j--;
    }
    return out;
}

The same problem in another language

More patterns problems in Java