Reverse Array


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


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

  1. Initialize two pointers:

    • s = 0 (start)

    • e = arr.length - 1 (end)

  2. While s < e:

    • Swap arr[s] and arr[e]

    • Increment s and decrement e

  3. 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 < e to avoid unnecessary swaps when s == e.


Time and Space Complexity


Dry Run

Input: arr = [1, 4, 3, 2, 6, 5]

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.