Challenge: Reverse in Place
Completed
Read n numbers into a vector and reverse it in place with two indexes that move toward each other and swap (no reverse(), no second vector). Print the result separated by spaces.
Input
Line 1: n. Line 2: n whole numbers.
Output
The numbers in reverse order.
Example
Input
4 1 2 3 4
Output
4 3 2 1
Editor
C++
Hints
left starts at 0, right at n - 1.
swap(v[left], v[right]), then move both inward until they meet.
Solution explanation
About n/2 swaps: O(n) time and O(1) extra space.
Show solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
int left = 0, right = n - 1;
while (left < right) {
swap(v[left], v[right]);
left++;
right--;
}
for (int i = 0; i < n; i++) cout << v[i] << (i + 1 < n ? " " : "\n");
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module