Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Array Reversal

Problem Statement

Write a Java program that reverses an array of integers in-place, meaning without using additional array storage beyond a few variables. The program should modify the input array such that the elements are arranged in reverse order and test the implementation with arrays of different sizes, including empty arrays and single-element arrays. You can visualize this as rearranging a row of numbered cards on a table by swapping pairs from the ends toward the center, without needing extra space to store a new row.

Input: An array of integers (e.g., arr = [1, 2, 3, 4, 5]). Output: The same array modified in-place to contain the elements in reverse order (e.g., [5, 4, 3, 2, 1]). Constraints:

  • The array length is between 0 and 10^5.
  • Elements are integers between -10^9 and 10^9.
  • The array may be empty. Example:
  • Input: arr = [1, 2, 3, 4, 5]
  • Output: [5, 4, 3, 2, 1]
  • Explanation: The array is reversed in-place by swapping elements from the ends toward the center.
  • Input: arr = []
  • Output: []
  • Explanation: An empty array remains unchanged.

Pseudocode

FUNCTION reverseArray(arr)
    IF arr is null OR length of arr <= 1 THEN
        RETURN
    ENDIF
    SET left to 0
    SET right to length of arr - 1
    WHILE left < right
        SET temp to arr[left]
        SET arr[left] to arr[right]
        SET arr[right] to temp
        INCREMENT left
        DECREMENT right
    ENDWHILE
ENDFUNCTION

Algorithm Steps

  1. Check if the input array is null or has 0 or 1 element. If so, return, as no reversal is needed.
  2. Initialize two pointers: left at the start of the array (index 0) and right at the end of the array (index length - 1).
  3. While left is less than right: a. Swap the elements at indices left and right using a temporary variable. b. Increment left and decrement right to move the pointers inward.
  4. Continue until left meets or exceeds right, at which point the array is fully reversed.
  5. Test the method with arrays of different sizes to verify correctness.

Java Implementation

public class ArrayReversal {
    // Reverses an array in-place
    public void reverseArray(int[] arr) {
        // Check for null or single-element/empty array
        if (arr == null || arr.length <= 1) {
            return;
        }
        // Initialize pointers
        int left = 0;
        int right = arr.length - 1;
        // Swap elements from ends toward center
        while (left < right) {
            // Swap using temporary variable
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            // Move pointers
            left++;
            right--;
        }
    }
}

Output

For the input array [1, 2, 3, 4, 5], the program modifies it to:

[5, 4, 3, 2, 1]

Explanation: The array is reversed in-place by swapping elements: (1 ↔ 5), (2 ↔ 4), leaving the middle element 3 in place.

For an empty array [], the program outputs:

[]

Explanation: An empty array remains unchanged.

For a single-element array [7], the program outputs:

[7]

Explanation: A single-element array is already reversed.

How It Works

  • Step 1: The reverseArray method checks if the array is null or has 0 or 1 element. For [1, 2, 3, 4, 5], it proceeds.
  • Step 2: Initialize left = 0, right = 4.
  • Step 3: Iterate while left < right:
    • First iteration: Swap arr[0] = 1 and arr[4] = 5, resulting in [5, 2, 3, 4, 1]. Set left = 1, right = 3.
    • Second iteration: Swap arr[1] = 2 and arr[3] = 4, resulting in [5, 4, 3, 2, 1]. Set left = 2, right = 2.
    • Stop: left = 2 >= right = 2, so the loop ends.
  • Example Trace: For [1, 2, 3, 4, 5], swaps (1 ↔ 5), (2 ↔ 4), resulting in [5, 4, 3, 2, 1].
  • In-Place Property: The algorithm uses only a single temporary variable, ensuring O(1) extra space regardless of array size.

Complexity Analysis Table

OperationTime ComplexitySpace Complexity
SwappingO(n/2) = O(n)O(1)
Full AlgorithmO(n)O(1)

Note:

  • n is the size of the input array.
  • Time complexity: O(n), as the algorithm performs n/2 swaps, each taking constant time.
  • Space complexity: O(1), as only a single temporary variable is used for swapping.
  • Best, average, and worst cases are O(n), as all elements are processed up to the midpoint.

✅ Tip: Use two pointers to reverse arrays in-place for optimal space efficiency. Test with large arrays (e.g., 10^4 elements) and edge cases like empty or single-element arrays to ensure robustness.

⚠ Warning: Ensure the input array is not null to avoid NullPointerException. Be cautious with very large arrays, as accessing invalid indices could occur if pointers are mismanaged.