You are given an array of integers arr[]. You have to reverse the given array.
Note: Modify the array in place.
Examples:
Input: arr = [1, 4, 3, 2, 6, 5] Output: [5, 6, 2, 3, 4, 1]
Explanation: The elements of the array are [1, 4, 3, 2, 6, 5]. After reversing the array, the first element goes to the last position, the second element goes to the second last position and so on. Hence, the answer is [5, 6, 2, 3, 4, 1].
Input: arr = [4, 5, 2] Output: [2, 5, 4]
Explanation: The elements of the array are [4, 5, 2]. The reversed array will be [2, 5, 4].
Input: arr = [1] Output: [1]
Explanation: The array has only single element, hence the reversed array is same as the original.
Constraints:
1 ≤ arr.size() ≤ 105
0 ≤ arr[i] ≤ 105
C++ Solution
Method 1: Using two-pointer technique
#include <iostream>
#include <vector>
using namespace std;
void reverseArray(vector<int>& arr) {
int start = 0, end = arr.size() - 1;
while (start < end) {
swap(arr[start], arr[end]);
start++;
end--;
}
}
int main() {
vector<int> arr = {1, 2, 3, 4, 5};
reverseArray(arr);
for (int x : arr) {
cout << x << " ";
}
return 0;
}
Python Solution:
arr = [1, 2, 3, 4, 5]
arr = arr[::-1]
print(arr)
Method 2: Using two-pointer loop
arr = [1, 2, 3, 4, 5]
start, end = 0, len(arr) - 1
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
print(arr)
Java Solution:
Method 1: Two-pointer method
public class Main {
public static void reverseArray(int[] arr) {
int start = 0, end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
reverseArray(arr);
for (int x : arr) {
System.out.print(x + " ");
}
}
}