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.
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.
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
0must move to indexn - 1. - The element at index
1must move to indexn - 2. - In general, index
iswaps places with indexn - 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.
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)#
- Set
left = 0andright = n - 1. - While
left < right, swaparr[left]andarr[right]. - Move
leftone step right andrightone step left. - Stop when the pointers meet or cross. The array is now reversed.
| Approach | Time | Extra space | In place? |
|---|---|---|---|
| Extra array | O(n) | O(n) | No |
| Two pointers | O(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.
L = 0,R = 4: swap 1 and 5, giving[5, 2, 3, 4, 1].L = 1,R = 3: swap 2 and 4, giving[5, 4, 3, 2, 1].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#
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#
#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++#
#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#
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 1Python#
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 1Complexity analysis#
- Time: O(n). We do
n / 2swaps, 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 < rightis 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
ifrom 0 tonand swapping withn - 1 - i: this swaps every pair twice and puts the array back in its original order. Stop at the middle.
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
ibelongs at indexn - 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 andO(1)extra space. - The same pattern solves palindrome checks, reversing a string and pair sum in a sorted array.