Practice › Arrays
Reverse an Array
Easy · Arrays · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Reverse the array in place and print it.
Input
First line: n. Second line: n space-separated integers.
Output
The reversed array, space-separated.
Constraints
- 1 ≤ n ≤ 10^5
- −10^9 ≤ a[i] ≤ 10^9
Swap a[i] with a[n − 1 − i] for i from 0 up to the middle — two pointers moving towards each other.
Example 1
Input
5 1 2 3 4 5
Output
5 4 3 2 1
Example 2
Input
1 7
Output
7
Hints
- Swap the first and last elements, then the second and second-last, and so on.
- Stop when the two pointers meet.
Approach
Use i = 0 and j = n − 1; swap a[i] and a[j], then move i forward and j backward while i < j. Each element moves once, and no second array is needed.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> a(n);
for (auto &x : a) cin >> x;
for (int i = 0, j = n - 1; i < j; i++, j--) swap(a[i], a[j]);
for (int i = 0; i < n; i++) cout << a[i] << (i + 1 < n ? ' ' : '\n');
return 0;
}Python solution
import sys
data = sys.stdin.read().split()
n = int(data[0])
a = data[1 : 1 + n]
i, j = 0, n - 1
while i < j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
print(" ".join(a))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] a = br.readLine().trim().split("\\s+");
for (int i = 0, j = n - 1; i < j; i++, j--) {
String t = a[i];
a[i] = a[j];
a[j] = t;
}
System.out.println(String.join(" ", a));
}
}