ArrayProblem 1 of 36

Reverse the array

Brute Force
Time: O(n)
Space: O(n)
Optimal
Time: O(n)
Space: O(1)

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

  1. Create a new array of same size
  2. Traverse original array from end to start
  3. 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

  1. Initialize left = 0 and right = n - 1
  2. While left < right:
    • Swap arr[left] and arr[right]
    • Increment left, decrement right
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

  1. Two-pointer technique is a common pattern for array problems
  2. In-place operations save memory when possible
  3. The optimal solution does exactly n/2 swaps