Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Reverse an Array: Two Pointer Approach in Java, C, C++, JavaScript and Python

Learn how to reverse an array in place with the two pointer technique. Step-by-step intuition, animated dry run, and solutions in Java, C, C++, JavaScript and Python.

Sumit KumarUpdated Oct 8, 20264 min readDSA
Reverse an Array: Two Pointer Approach in Java, C, C++, JavaScript and Python

Reversing an array is usually the very first problem on any DSA sheet. It looks trivial, but it teaches you the two pointer technique, one of the most useful patterns in coding interviews. In this post you will learn how to think about the problem, see it animated step by step, and get clean solutions in Java, C, C++, JavaScript and Python.

Problem statement#

Given an array arr of n integers, reverse the array in place, so the first element becomes the last, the second becomes the second last, and so on.

Text
Input:  [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]

Input:  [4, 7]
Output: [7, 4]

How to think about this problem#

Before writing any code, ask yourself: where does each element need to go?

  • The element at index 0 must move to index n - 1.
  • The element at index 1 must move to index n - 2.
  • In general, index i swaps places with index n - 1 - i.

Notice that each swap fixes two positions at once: one at the front and one at the back. So we only need to walk until the middle. That observation leads straight to two pointers: one starting at the left end, one at the right end, moving towards each other.

Tip

Whenever a problem pairs up elements from the two ends of an array (reverse, palindrome check, pair sum in a sorted array), think "two pointers moving inward".

Approaches#

Approach 1: Use an extra array#

Create a new array and copy elements from the end of the original into the start of the new one. It is easy, but it uses O(n) extra memory, and the problem asks us to reverse in place.

Approach 2: Two pointers (optimal)#

  1. Set left = 0 and right = n - 1.
  2. While left < right, swap arr[left] and arr[right].
  3. Move left one step right and right one step left.
  4. Stop when the pointers meet or cross. The array is now reversed.
ApproachTimeExtra spaceIn place?
Extra arrayO(n)O(n)No
Two pointersO(n)O(1)Yes

Dry run (animated)#

Here is the two pointer approach on [1, 2, 3, 4, 5]. Orange boxes are the pair being swapped, green boxes are already in their final place.

Animation: two pointers L and R swap 1 and 5, then 2 and 4, until they meet and the array becomes 5 4 3 2 1
  1. L = 0, R = 4: swap 1 and 5, giving [5, 2, 3, 4, 1].
  2. L = 1, R = 3: swap 2 and 4, giving [5, 4, 3, 2, 1].
  3. L = 2, R = 2: the pointers meet. The middle element 3 is already in place, so we stop.

Only 2 swaps were needed for 5 elements, that is n / 2 swaps.

Code#

Java#

Java
import java.util.Arrays;

public class Main {
    static void reverse(int[] arr) {
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        reverse(arr);
        System.out.println(Arrays.toString(arr)); // [5, 4, 3, 2, 1]
    }
}

C#

C
#include <stdio.h>

void reverse(int arr[], int n) {
    int left = 0, right = n - 1;
    while (left < right) {
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
}

int main(void) {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    reverse(arr, n);
    for (int i = 0; i < n; i++) printf("%d ", arr[i]); // 5 4 3 2 1
    printf("\n");
    return 0;
}

C++#

CPP
#include <iostream>
#include <vector>
using namespace std;

void reverseArray(vector<int>& arr) {
    int left = 0, right = (int)arr.size() - 1;
    while (left < right) {
        swap(arr[left], arr[right]);
        left++;
        right--;
    }
}

int main() {
    vector<int> arr = {1, 2, 3, 4, 5};
    reverseArray(arr);
    for (int x : arr) cout << x << " "; // 5 4 3 2 1
    cout << endl;
    return 0;
}

JavaScript#

JavaScript
function reverse(arr) {
  let left = 0;
  let right = arr.length - 1;
  while (left < right) {
    [arr[left], arr[right]] = [arr[right], arr[left]];
    left++;
    right--;
  }
  return arr;
}

console.log(reverse([1, 2, 3, 4, 5]).join(" ")); // 5 4 3 2 1

Python#

Python
def reverse(arr):
    left, right = 0, len(arr) - 1
    while left < right:
        arr[left], arr[right] = arr[right], arr[left]
        left += 1
        right -= 1
    return arr


print(*reverse([1, 2, 3, 4, 5]))  # 5 4 3 2 1

Complexity analysis#

  • Time: O(n). We do n / 2 swaps, and constants are dropped.
  • Space: O(1). Only two index variables and one temporary value, no matter how large the array is.

Edge cases and common mistakes#

  • Empty array or one element: left < right is false immediately, so nothing happens. That is the correct answer.
  • Even length: the pointers cross instead of meeting. The loop condition still stops correctly.
  • Using left <= right: it still works, but it wastes one swap of the middle element with itself.
  • Looping i from 0 to n and swapping with n - 1 - i: this swaps every pair twice and puts the array back in its original order. Stop at the middle.
Note

Most languages have a built-in: std::reverse in C++, arr.reverse() in JavaScript, and arr.reverse() or arr[::-1] in Python. Java's Collections.reverse works on a List, not on a plain int[], which is one more reason to know the two pointer version. In an interview, write the two pointer version first, then mention the built-in.

Key takeaways#

  • Element at index i belongs at index n - 1 - i, so swap pairs from both ends.
  • Two pointers moving inward fix two positions per swap and stop at the middle.
  • The solution runs in O(n) time and O(1) extra space.
  • The same pattern solves palindrome checks, reversing a string and pair sum in a sorted array.