Reverse a list end to end
A replay view shows the most recent reading first, so the buffer has to come back the other way round.
- The order reverses; the values themselves are untouched.
- An empty list and a single reading both come back as they went in.
reverseReadings(readings: list<int>) → list<int>
C++ 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.
Where you start
std::vector<int> reverseReadings(std::vector<int> readings) {
}
Worked examples
| Call | Result |
|---|---|
reverseReadings(std::vector<int>{1, 2, 3}) | std::vector<int>{3, 2, 1} |
reverseReadings(std::vector<int>{1, 2, 3, 4}) | std::vector<int>{4, 3, 2, 1} |
reverseReadings(std::vector<int>{7}) | std::vector<int>{7} |
reverseReadings(std::vector<int>{}) | std::vector<int>{} |
Hint
Put one index at each end. Swap what they point at, then step them towards each other until they meet.
Reference solution in C++
std::vector<int> reverseReadings(std::vector<int> readings) {
std::vector<int> out = readings;
int i = 0, j = static_cast<int>(out.size()) - 1;
while (i < j) {
std::swap(out[i], out[j]);
i++;
j--;
}
return out;
}