You are given an array of integers arr[].
Your task is to reverse the given array in place.
That means no extra array β just flip it inside out, right where it is! π
Input:
arr = [1, 4, 3, 2, 6, 5]Output:
[5, 6, 2, 3, 4, 1]
Explanation:
- Original array:
1 4 3 2 6 5 - After reversing:
5 6 2 3 4 1
Input:
arr = [4, 5, 2]Output:
[2, 5, 4]
Explanation:
- Start with two pointers: i = 0, j = 2
- Swap arr[0] and arr[2] β [2, 5, 4]
- Now i = 1, j = 1 (both meet at the center), so stop.
- Final result is the reversed array: [2, 5, 4]
Input:
arr = [1]Output:
[1]
Explanation:
Single element remains unchanged.
π‘ Idea:
We simply swap elements from both ends moving toward the center.
βοΈ Steps:
- Start with two pointers β one at the beginning (
i), and one at the end (n - i - 1). - Keep swapping these elements until you reach the middle.
- Done! π
This is the classic in-place reverse strategy β minimal and elegant!
| Complexity | Value | Reason |
|---|---|---|
| π Time | O(n/2) β O(n) |
Half swaps, but still linear in nature |
| π¦ Space | O(1) |
In-place, no extra memory used |
1 β€ arr.length β€ 10β΅0 β€ arr[i] β€ 10β΅
class Solution {
public void reverseArray(int arr[]) {
int n = arr.length;
for(int i = 0; i < n / 2; i++){
int temp = arr[n - i - 1];
arr[n - i - 1] = arr[i];
arr[i] = temp;
}
}
}Made with β€οΈ by Milan Haria