Reverse Array
Problem Link
Reverse an Array – GeeksforGeeks
Problem: Reverse an Array
Problem Statement
You are given an array of integers arr[]. Your task is to reverse the given array in place.
Note: Modify the array in-place without using extra space for another array.
Examples
Example 1
Input: arr = [1, 4, 3, 2, 6, 5]
Output: [5, 6, 2, 3, 4, 1]
Explanation: Elements are reversed by swapping from both ends toward the center.
Example 2
Input: arr = [4, 5, 2]
Output: [2, 5, 4]
Example 3
Input: arr = [1]
Output: [1]
Explanation: A single-element array remains the same after reversal.
Constraints
-
1 <= arr.length <= 10⁵ -
0 <= arr[i] <= 10⁵
Intuition
Reversing an array means swapping the first element with the last, the second with the second last, and so on. This two-pointer technique allows in-place reversal with minimal time and space.
Approach
-
Initialize two pointers:
-
s = 0(start) -
e = arr.length - 1(end)
-
-
While
s < e:-
Swap
arr[s]andarr[e] -
Increment
sand decremente
-
-
Stop when pointers meet or cross.
Code (Java)
class Solution {
public void reverseArray(int arr[]) {
int n = arr.length;
for (int s = 0, e = n - 1; s < e; s++, e--) {
int temp = arr[s];
arr[s] = arr[e];
arr[e] = temp;
}
}
}
Note: Corrected loop condition to
s < eto avoid unnecessary swaps whens == e.
Time and Space Complexity
-
Time Complexity:
O(n / 2)⇒O(n)
Each element is visited once in a pairwise swap. -
Space Complexity:
O(1)
Swaps are done in-place without any additional data structures.
Dry Run
Input: arr = [1, 4, 3, 2, 6, 5]
-
s = 0,e = 5→ swap1and5→[5, 4, 3, 2, 6, 1] -
s = 1,e = 4→ swap4and6→[5, 6, 3, 2, 4, 1] -
s = 2,e = 3→ swap3and2→[5, 6, 2, 3, 4, 1] -
Loop ends as
s = 3,e = 2
Output: [5, 6, 2, 3, 4, 1]
Conclusion
This problem is a classic example of the two-pointer approach for in-place operations. The algorithm is simple, efficient, and optimal in both time and space for reversing arrays of any size.