Advertisement
Home Data Structure Arrays Reverse Half of an Array

Reverse Half of an Array

0
Advertisement

Title: Reverse Half of an Array

In this guide, you’ll learn how to reverse the first half of an integer array in place while leaving the second half exactly where it is. It is a classic warm-up on two-pointer loops and index arithmetic, and interviewers lean on it because the pitfalls are almost entirely about where the loop stops rather than how a swap works.

We will walk through the problem statement, build a short Java method, trace it on a fresh input, and then look at the common off-by-one slips, the boundary inputs worth checking, and the follow-up questions a real interviewer tends to ask next.

Understanding the Problem

Given an integer array numbers of length n, reverse only the first half of the array in place. The first half is defined as the first n / 2 elements, using integer division. For an even-length array of six elements the first three positions are flipped end to end; for an odd-length array of five elements the first two positions are flipped and the middle element stays untouched.

The algorithm must mutate the input array directly rather than return a new copy, and it must leave the second half of numbers unchanged. Running on an empty or single-element array is a valid no-op; running on a null reference is a programmer error we surface loudly.

Approach

The cleanest way to reverse a prefix of an array is the two-pointer swap, bounded to the half-length index range.

  1. Reject a null input early by throwing IllegalArgumentException so the problem surfaces at the call site.
  2. Compute half = numbers.length / 2. Integer division already handles odd lengths correctly.
  3. Initialize two pointers: left = 0 and right = half - 1.
  4. While left < right, swap numbers[left] with numbers[right] through a temporary variable.
  5. Advance left forward by one and right backward by one at the end of every iteration.
  6. Stop when the pointers meet or cross. The first half is now reversed and the second half is untouched.

Java Program

Java
public class ReverseHalfOfAnArray {

    public static void reverseFirstHalf(int[] numbers) {
        if (numbers == null) {
            throw new IllegalArgumentException("Array must not be null");
        }
        int left = 0;
        int right = numbers.length / 2 - 1;
        while (left < right) {
            int temp = numbers[left];
            numbers[left] = numbers[right];
            numbers[right] = temp;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6};
        reverseFirstHalf(numbers);
        System.out.print("Result: ");
        for (int value : numbers) {
            System.out.print(value + " ");
        }
    }
}

Explanation of the Program

The reverseFirstHalf method first guards against a null array and then establishes the swap window. Setting right = numbers.length / 2 - 1 is the critical detail; it ensures that only the first n / 2 positions are considered and the middle element of an odd-length array stays in place.

The while loop performs a standard in-place swap through a temp local, then shrinks the window from both ends. The loop condition left < right stops the loop the moment the two pointers meet, which prevents an element from being swapped with itself and prevents a swap that would undo the previous one.

The main method shows the method in use. It builds a six-element array, calls reverseFirstHalf, and prints the result with an enhanced for loop so you can see the mutated array directly in the console.

Step-by-Step Trace

Suppose the input is {5, 2, 7, 4, 1, 8, 3, 6}. The length is 8, so half is 4, left starts at 0, and right starts at 3. The expected final array is {4, 7, 2, 5, 1, 8, 3, 6}, with the first four positions reversed and the last four untouched.

IterationleftrightArray before swapArray after swap
103{5, 2, 7, 4, 1, 8, 3, 6}{4, 2, 7, 5, 1, 8, 3, 6}
212{4, 2, 7, 5, 1, 8, 3, 6}{4, 7, 2, 5, 1, 8, 3, 6}

At the end of each iteration, the sub-array between left and right is the only region left to reverse, and everything outside it is already in its final position. When left meets or passes right, the first half is fully reversed and the loop exits.

Examples

Example 1: Even-length Array

With four elements, half is 2 and only the first two positions are swapped.

Java
int[] numbers = {1, 2, 3, 4};
reverseFirstHalf(numbers);
// Output: 2 1 3 4

Example 2: Odd-length Array

For an odd length of five, half is 2. The first two elements swap and the middle element at index 2 stays exactly where it was.

Java
int[] numbers = {10, 20, 30, 40, 50};
reverseFirstHalf(numbers);
// Output: 20 10 30 40 50

Example 3: Larger Even-length Array

With eight elements, half is 4 and the first four positions are reversed end to end.

Java
int[] numbers = {11, 22, 33, 44, 55, 66, 77, 88};
reverseFirstHalf(numbers);
// Output: 44 33 22 11 55 66 77 88

Common Mistakes to Avoid

The errors on this problem almost always live in the loop bounds rather than in the swap itself.

  • Reversing the entire array – setting right = numbers.length - 1 flips the whole array instead of the first half. Set right = numbers.length / 2 - 1 so the swap window stops at the midpoint.
  • Including the midpoint on odd lengths – using right = numbers.length / 2 drags the middle element into the swap on inputs like {1, 2, 3, 4, 5} and produces {3, 2, 1, 4, 5} instead of {2, 1, 3, 4, 5}. Subtract one so the middle element stays put.
  • Advancing only one pointer – forgetting left++ or right-- locks the loop into an infinite swap on the same pair of indices. Update both pointers at the end of every iteration.
  • Returning a new array – allocating a fresh array and returning it leaves the caller’s original reference pointing at unchanged data, so the assertion numbers[0] == 2 fails silently. Mutate the parameter in place instead.
  • Using <= as the loop condition – on an odd half-length such as three, the pointers meet in the middle and the condition left <= right performs a self-swap that is harmless but confusing to explain during a trace. Prefer < so the loop stops the instant the pointers meet.

Edge Cases to Test

Walk through the following inputs before you call the method done.

  • Empty array
  • Single-element array
  • Two-element array
  • Odd-length array with a middle element
  • Even-length array where the half is itself a single element
  • All identical elements
  • Array containing Integer.MIN_VALUE and Integer.MAX_VALUE
  • Null array reference

Additional Considerations

The algorithm runs in O(n) time, where n is the length of the input array; the work per element is a constant-time swap and each element in the first half is visited at most once. More precisely, the number of swaps is exactly numbers.length / 2 / 2, which is still linear in n.

Space complexity is O(1). The method only allocates a single temp local for the swap, and the first-half reversal happens entirely in place on the input array. No auxiliary array is required, which is the key advantage over a naive copy, reverse, and write-back approach.

Integer overflow is not a concern here because the method only moves values; it never performs arithmetic on them. That means Integer.MIN_VALUE and Integer.MAX_VALUE can appear anywhere in the input without affecting the result or risking a wraparound.

Interview Follow-up Questions

A base implementation is only the first ten minutes; here is how the conversation usually widens from there.

  • What if you need to reverse the second half instead? – mirror the pointer setup so that left starts at numbers.length / 2 (or (numbers.length + 1) / 2 if you want to skip the middle element on odd lengths) and right starts at numbers.length - 1.
  • What if the first half must be reversed into a new array, leaving the input untouched? – clone the input with Arrays.copyOf first and run the same two-pointer swap on the copy, trading O(1) auxiliary space for O(n).
  • What if the problem generalizes to reversing every k-length block of the array? – loop over block start indices 0, k, 2k, ... and apply the two-pointer swap to each block, treating the last partial block as its own sub-problem.
  • What if the structure is a singly linked list rather than an array? – use a slow and fast pointer pair to locate the midpoint in one pass, then run the standard three-pointer list-reversal pattern over the first half; the two-pointer array trick no longer works because random access is O(n).
  • What if the input arrives as a stream and you can only read each element once? – push the first half of the stream onto a stack, pop the stack as the midpoint arrives to produce the reversed prefix, and then forward the remaining stream elements unchanged.

Conclusion

Reversing only the first half of an array is a tiny program that trains a very useful habit: thinking about the swap window as a half-open interval and letting integer arithmetic draw the boundary for you. Once numbers.length / 2 is in your head as the exclusive upper bound, the follow-up variants on second halves, k-length blocks, and linked lists all come from the same shape.

Adapt the code to your own inputs and try the follow-up questions before you look up the standard answers; the extra ten minutes of struggle is where the interview-level fluency actually comes from. You can learn more about array algorithms here: Arrays.