Video in progress

Reverse an array in place, without allocating another array.

Take two pointers, one at the start and one at the end. Swap them, move toward each other, and stop when they meet. Time is O(n), extra memory is O(1).

📖 Answer

static void reverse(int[] a) {
    int i = 0, j = a.length - 1;
    while (i < j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
        i++;
        j--;
    }
}

The loop covers only half the array: n/2 swaps. The condition is i < j: with odd length the middle element stays where it is, and with even length the pointers cross each other.

Call out the edge cases yourself: on an empty array and a one-element array the loop doesn't run at all, which is the correct behavior. Ask the interviewer what should happen on null, or check for it up front.

This template shows up in many places later: palindrome checks, reversing the words in a text, rotating an array by k steps.