Day 3 - Reverse an Array
π Day 3. Reverse an Array π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
You are given an array of integers arr[]
. Your task is to reverse the given array.
π Example Walkthrough:
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 a single element, hence the reversed array is the same as the original.
Constraints:
$
1 <= arr.size() <= 10^5
$$
0 <= arr[i] <= 10^5
$
π― My Approach:
Reversal Process:
The main idea is to reverse the array in-place by swapping elements from both ends.
We initialize two pointers:
left
at the beginning of the array andright
at the end.We swap
arr[left]
andarr[right]
, then moveleft
forward andright
backward until they cross each other.This process effectively reverses the array.
Alternative Approaches:
XOR Swap Method: You can swap elements using XOR to avoid a temporary variable.
Using List Reverse: In some languages, you can simply call the reverse function on the array.
π Time and Auxiliary Space Complexityπ
Expected Time Complexity: O(n), where
n
is the number of elements in the array. We perform one pass through the array, swapping elements in place.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space to track the left and right pointers.
π Solution Code
Code (C)
void reverseArray(int arr[], int n) {
int left = 0, right = n - 1;
while (left < right) {
arr[left] ^= arr[right];
arr[right] ^= arr[left];
arr[left] ^= arr[right];
left++;
right--;
}
}
Code (CPP)
class Solution {
public:
void reverseArray(std::vector<int>& arr) {
std::reverse(arr.begin(), arr.end());
}
};
Code (Java)
class Solution {
public void reverseArray(int[] arr) {
Integer[] boxedArray = Arrays.stream(arr).boxed().toArray(Integer[]::new);
List<Integer> list = Arrays.asList(boxedArray);
Collections.reverse(list);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
}
}
Code (Python)
class Solution:
def reverseArray(self, arr):
arr.reverse()
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated