Challenge: Reverse in Place

Lab C++ Beginner 10 points

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
Sample input available Sample output available
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
HOME LABS COMMUNITY DASHBOARD