Java Program to Reverse an Array in Place (Two-Pointer Approach)

Reversing an array means rearranging its elements so that the first element becomes the last, the second element becomes the second-to-last, and so on.

For example, consider the array {10, 20, 30, 40, 50}. After reversing it, the elements become {50, 40, 30, 20, 10}.

In Java, you can reverse an array by creating another array and copying elements in reverse order. However, many coding interviews ask you to reverse an array in place. This means modifying the original array without creating a second array to store the reversed elements.

The most efficient approach uses two pointers. One pointer starts at the beginning of the array, and the other starts at the end. The program swaps the elements at these positions and moves both pointers toward the center.

In this tutorial, I will explain how to reverse an array in place in Java using the two-pointer technique. I will also demonstrate a recursive solution, explain the time and space complexity, and cover important edge cases.

What Does Reversing an Array in Place Mean?

Reversing an array in place means changing the order of elements inside the existing array without creating another array for the result.

Consider the following integer array:

int[] numbers = {10, 20, 30, 40, 50};

Before reversing:

[10, 20, 30, 40, 50]

After reversing:

[50, 40, 30, 20, 10]

The original array is modified directly. No additional array is required.

Why Is In-Place Reversal Useful?

In-place reversal is useful when you want to rearrange array elements while minimizing additional memory usage.

It is also a common application of the two-pointer technique, which appears in many array and string interview problems.

The same technique can be adapted to reverse part of an array, rotate an array, and solve certain palindrome-related problems.

Method 1: Reverse an Array in Place Using Two Pointers

The two-pointer approach is the recommended solution for reversing an array in place.

The algorithm uses two indexes:

  • left starts at index 0, which points to the first element.
  • right starts at index array.length - 1, which points to the last element.

During each iteration, the program swaps the elements at these indexes.

After swapping, left moves one position forward and right moves one position backward.

The process continues until the two pointers meet or cross.

Java Program

Create a Java class named ReverseArrayInPlaceExample and add the following code:

import java.util.Arrays;
import java.util.Objects;

public class ReverseArrayInPlaceExample {

    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

        System.out.println("Original array: "
                + Arrays.toString(numbers));

        reverseArray(numbers);

        System.out.println("Reversed array: "
                + Arrays.toString(numbers));
    }

    /**
     * Reverses the elements of an integer array in place.
     *
     * @param numbers the array to reverse
     * @throws NullPointerException if the array is null
     */
    public static void reverseArray(int[] numbers) {

        Objects.requireNonNull(numbers, "Array must not be null");

        int left = 0;
        int right = numbers.length - 1;

        // Swap elements until the pointers meet.
        while (left < right) {

            // Save the left element temporarily.
            int temp = numbers[left];

            // Move the right element to the left position.
            numbers[left] = numbers[right];

            // Move the saved element to the right position.
            numbers[right] = temp;

            // Move both pointers toward the center.
            left++;
            right--;
        }
    }
}

Output

Original array: [10, 20, 30, 40, 50]
Reversed array: [50, 40, 30, 20, 10]

How Does the Program Work?

The program starts with an integer array containing five elements.

It then calls the reverseArray() method, which reverses the elements of the same array.

Step 1: Initialize Two Pointers

int left = 0;
int right = numbers.length - 1;

The left pointer identifies the first element, while right identifies the last element.

For an array of five elements:

left = 0
right = 4

Step 2: Swap the Elements

The program swaps the values at the two pointer positions:

int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;

The temporary variable stores one value while the two elements are exchanged.

Although this code uses a temporary variable, the algorithm is still an in-place reversal because it does not create another array. It uses only a constant amount of additional memory.

Step 3: Move the Pointers

left++;
right--;

After every swap, the left pointer moves forward and the right pointer moves backward.

This allows the algorithm to process the next pair of elements.

Step 4: Stop When the Pointers Meet

The loop uses this condition:

while (left < right)

When left becomes greater than or equal to right, all necessary swaps have been completed.

Step-by-Step Dry Run: Reversing an Array

Consider the array:

[10, 20, 30, 40, 50]

Initially, left = 0 and right = 4.

Step Elements Swapped Array After Swapping
Initial None [10, 20, 30, 40, 50]
1 10 and 50 [50, 20, 30, 40, 10]
2 20 and 40 [50, 40, 30, 20, 10]

After the second swap, both pointers reach index 2.

The middle element, 30, remains in the same position because it does not need to be swapped.

The final reversed array is:

[50, 40, 30, 20, 10]

Method 2: Reverse an Array in Place Using Recursion

You can also reverse an array using recursion.

Recursion means that a method calls itself to solve a smaller version of the same problem.

In this approach, the recursive method swaps the first and last elements, then calls itself to reverse the remaining portion of the array.

The recursion stops when the left pointer reaches or crosses the right pointer.

Java Program

import java.util.Arrays;
import java.util.Objects;

public class ReverseArrayUsingRecursion {

    public static void main(String[] args) {

        int[] numbers = {1, 2, 3, 4, 5, 6};

        System.out.println("Original array: "
                + Arrays.toString(numbers));

        reverseArray(numbers);

        System.out.println("Reversed array: "
                + Arrays.toString(numbers));
    }

    /**
     * Reverses an array using a recursive helper method.
     *
     * @param numbers the array to reverse
     * @throws NullPointerException if the array is null
     */
    public static void reverseArray(int[] numbers) {

        Objects.requireNonNull(numbers, "Array must not be null");

        reverseRecursive(numbers, 0, numbers.length - 1);
    }

    /**
     * Reverses the portion of an array between two indexes.
     */
    private static void reverseRecursive(
            int[] numbers, int left, int right) {

        // Base case: all required swaps are complete.
        if (left >= right) {
            return;
        }

        // Exchange the elements at both ends.
        int temp = numbers[left];
        numbers[left] = numbers[right];
        numbers[right] = temp;

        // Reverse the remaining elements.
        reverseRecursive(numbers, left + 1, right - 1);
    }
}

Output

Original array: [1, 2, 3, 4, 5, 6]
Reversed array: [6, 5, 4, 3, 2, 1]

How Does the Recursive Program Work?

The program starts by calling reverseArray(numbers).

This method validates the array and calls the recursive helper with the first and last indexes.

The recursive calls process the following pairs:

reverseRecursive(numbers, 0, 5)
reverseRecursive(numbers, 1, 4)
reverseRecursive(numbers, 2, 3)
reverseRecursive(numbers, 3, 2)

The first call swaps elements at indexes 0 and 5.

The second call swaps elements at indexes 1 and 4.

The third call swaps elements at indexes 2 and 3.

In the fourth call, the left index is greater than the right index. The base case is reached, and recursion stops.

The original array has now been reversed.

Important: The recursive solution modifies the array in place, but it uses additional memory for recursive method calls. Therefore, it does not achieve constant extra space.

Method 3: Reverse an Array Using Another Array

Another common approach is to create a new array and copy the elements in reverse order.

This approach is not in place because it allocates a second array. However, it is useful when the original array must remain unchanged.

Java Program

import java.util.Arrays;
import java.util.Objects;

public class ReverseArrayUsingNewArray {

    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40};

        int[] reversed = reverseArray(numbers);

        System.out.println("Original array: "
                + Arrays.toString(numbers));

        System.out.println("Reversed array: "
                + Arrays.toString(reversed));
    }

    /**
     * Returns a new array containing the elements
     * of the input array in reverse order.
     *
     * @param numbers the source array
     * @return a new reversed array
     * @throws NullPointerException if the array is null
     */
    public static int[] reverseArray(int[] numbers) {

        Objects.requireNonNull(numbers, "Array must not be null");

        int[] reversed = new int[numbers.length];

        for (int i = 0; i < numbers.length; i++) {

            // Copy elements from the end of the source array.
            reversed[i] = numbers[numbers.length - 1 - i];
        }

        return reversed;
    }
}

Output

Original array: [10, 20, 30, 40]
Reversed array: [40, 30, 20, 10]

Explanation

The program creates a new array with the same length as the input array.

It then copies elements from the original array in reverse order.

The first element of the new array receives the last element of the original array. The second element receives the second-to-last element, and so on.

This method preserves the original array, but it requires additional memory proportional to the array size.

How to Run the Java Programs

You can run these examples using IntelliJ IDEA, Eclipse, Visual Studio Code, or the command line.

Follow these steps to run the two-pointer example:

  1. Install a Java Development Kit (JDK).
  2. Create a Java file named ReverseArrayInPlaceExample.java.
  3. Copy the code from Method 1 into the file.
  4. Open a terminal in the folder containing the file.
  5. Compile the program:
javac ReverseArrayInPlaceExample.java

Run the program:

java ReverseArrayInPlaceExample

The program prints the original and reversed arrays.

For the other examples, save each class in a file matching its public class name.

Handling Important Edge Cases

The two-pointer approach works for arrays of different lengths and values.

Input Array Reversed Array
{1, 2, 3, 4, 5} {5, 4, 3, 2, 1}
{10, 20, 30, 40} {40, 30, 20, 10}
{7} {7}
{} {}
{-1, -2, -3} {-3, -2, -1}
{5, 5, 10, 10} {10, 10, 5, 5}
{0, -5, 10} {10, -5, 0}

What Happens with an Empty Array?

An empty array does not require any swaps.

For an array of length zero, the two-pointer method initializes right to -1. Since left < right is false, the loop never executes.

The array remains empty.

What Happens with a Single-Element Array?

A single-element array is already reversed.

Both pointers start at index 0, so the loop does not execute.

What Happens with a Null Array?

The examples use Objects.requireNonNull() to reject a null array with a descriptive error message.

A null reference does not refer to an array, so it cannot be reversed.

Time and Space Complexity

Let n represent the number of elements in the array.

Approach Time Complexity Extra Space
Two-pointer approach O(n) O(1)
Recursion O(n) O(n) call-stack space
New array O(n) O(n)

Why Is the Two-Pointer Approach O(n)?

The two-pointer approach performs approximately n / 2 swaps.

Each swap takes constant time, so the total time complexity is O(n).

The algorithm uses only two indexes and one temporary variable. Therefore, its extra space complexity is O(1).

This makes it suitable for large arrays when you want to avoid allocating another array.

Common Mistakes When Reversing an Array

1. Using the Wrong Last Index

Java array indexes start at zero.

For an array of length 5, the valid indexes are 0 through 4.

The correct last index is:

int right = numbers.length - 1;

Using numbers.length as an index causes an ArrayIndexOutOfBoundsException.

2. Using the Wrong Loop Condition

The two-pointer loop should continue while the left pointer is smaller than the right pointer.

while (left < right)

There is no need to swap the middle element of an odd-length array with itself.

3. Forgetting to Move the Pointers

After swapping two elements, update both pointers:

left++;
right--;

Without these updates, the loop may continue indefinitely.

4. Overwriting a Value During Swapping

Consider this incorrect swap:

numbers[left] = numbers[right];
numbers[right] = numbers[left];

The original left value is lost after the first assignment.

Use a temporary variable to preserve it while swapping.

5. Assuming Recursion Uses Constant Space

The recursive solution modifies the array without allocating another array, but each recursive call uses stack space.

For large arrays, the recursive approach may also cause a StackOverflowError.

The iterative two-pointer solution avoids this limitation.

Frequently Asked Questions

How do you reverse an array in Java without using another array?

Use two pointers. Start one at the beginning and the other at the end. Swap the elements and move the pointers toward the center until they meet.

What does in-place array reversal mean?

It means reversing the elements inside the original array without allocating a second array to hold the result.

Can I reverse an array using a for loop?

Yes. You can use a for loop with two indexes that move toward the center. The swapping logic remains the same as the while-loop approach.

Does Java provide Arrays.reverse()?

No. The standard Java Arrays utility class does not provide an Arrays.reverse() method for primitive arrays.

Java provides Collections.reverse() for lists, but that is different from reversing a primitive array such as int[].

Can I reverse an array recursively?

Yes. A recursive method can swap the first and last elements, then recursively process the remaining portion of the array.

Which approach is best for Java coding interviews?

The iterative two-pointer approach is generally the best choice. It takes O(n) time and uses O(1) extra space.

Does reversing an array change the original array?

Yes, if you use the two-pointer or recursive methods shown in this tutorial.

If you need to preserve the original order, create a separate reversed array instead.

Conclusion

In this tutorial, you learned how to reverse an array in Java using the two-pointer technique, recursion, and an additional array.

The two-pointer approach is the most efficient solution when the requirement is to reverse an array in place. It swaps elements from opposite ends and moves toward the center until the reversal is complete.

The recursive approach demonstrates how the same problem can be solved through smaller method calls. However, it uses additional stack memory. Creating a new array is useful when the original array must remain unchanged.

For Java coding interviews, I recommend practicing the iterative two-pointer solution first. Once you understand it, try using the same technique to reverse a portion of an array, rotate an array, or check whether an array is a palindrome.

Official Java Documentation

For more information about Java arrays and the APIs used in this tutorial, refer to the following official Oracle documentation:

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments