ArrayProblem 1 of 36
Reverse the array
Problem Statement
Given an array, reverse all the elements of the array.
Example:
- Input:
[1, 2, 3, 4, 5] - Output:
[5, 4, 3, 2, 1]
Approach 1: Brute Force (Using Extra Array)
Intuition
Create a new array and copy elements from the original array in reverse order.
Algorithm
- Create a new array of same size
- Traverse original array from end to start
- Copy each element to the new array
java
public class Solution {
public int[] reverseArray(int[] arr) {
int n = arr.length;
int[] reversed = new int[n];
for (int i = 0; i < n; i++) {
reversed[i] = arr[n - 1 - i];
}
return reversed;
}
}Complexity Analysis
- Time Complexity: O(n) - Single pass through the array
- Space Complexity: O(n) - Extra array of size n
Approach 2: Optimal (Two Pointer - In Place)
Intuition
Use two pointers, one at the start and one at the end. Swap elements and move pointers towards each other.
Algorithm
- Initialize
left = 0andright = n - 1 - While
left < right:- Swap
arr[left]andarr[right] - Increment
left, decrementright
- Swap
java
public class Solution {
public void reverseArray(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
// Swap elements
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}Complexity Analysis
- Time Complexity: O(n) - We traverse n/2 elements
- Space Complexity: O(1) - In-place reversal, no extra space
Key Takeaways
- Two-pointer technique is a common pattern for array problems
- In-place operations save memory when possible
- The optimal solution does exactly n/2 swaps