Reverse an Array
Reversing an array is a classic interview warm-up, and a good way to practice thinking with indexes. Picture a queue of people swapping places to face the other way: the first and last swap, then the second and second-last, and so on, until they meet in the middle. That two-pointer idea reverses an array in place, using no extra array.
Two Pointers, Swapping Inward
import java.util.Arrays;
public class Reverse {
public static void main(String[] args) {
int[] a = {10, 20, 30, 40, 50};
int left = 0;
int right = a.length - 1;
while (left < right) {
int temp = a[left];
a[left] = a[right];
a[right] = temp;
left++;
right--;
}
System.out.println(Arrays.toString(a));
}
}[50, 40, 30, 20, 10]How it works
leftstarts at the first index,rightat the last.- Lines 9 to 11 swap the two elements using a temporary variable. Without
temp, the first assignment would overwrite a value before it's copied. - Lines 12 and 13 move both pointers one step inward.
- The loop stops when
left < rightis false: the pointers have met (odd length) or crossed (even length).
Try it yourself: run it with an even-length array, {1, 2, 3, 4}. How many swaps happen?
The Same Idea with a for Loop
import java.util.Arrays;
public class ReverseFor {
public static void main(String[] args) {
String[] stops = {"Delhi", "Agra", "Gwalior", "Bhopal"};
for (int i = 0; i < stops.length / 2; i++) {
String temp = stops[i];
stops[i] = stops[stops.length - 1 - i];
stops[stops.length - 1 - i] = temp;
}
System.out.println(Arrays.toString(stops));
}
}[Bhopal, Gwalior, Agra, Delhi]The partner of index i is length - 1 - i. Looping to length / 2 does exactly half the swaps.
Or Build a New Array
When you must keep the original, fill a new array from the back:
import java.util.Arrays;
public class Reversed {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] r = new int[a.length];
for (int i = 0; i < a.length; i++) {
r[i] = a[a.length - 1 - i];
}
System.out.println(Arrays.toString(a) + " -> " + Arrays.toString(r));
}
}[1, 2, 3] -> [3, 2, 1]| Approach | Extra memory | Original kept? |
|---|---|---|
| Two pointers, in place | None | No |
| New array | One more array | Yes |
Common Mistakes
Looping over the whole array while swapping. Every pair is swapped twice, and the array ends up unchanged.
Swapping without temp. a[i] = a[j]; a[j] = a[i]; copies the same value into both.
Getting the partner index wrong. It's length - 1 - i, not length - i.
Interview Corner
How do you reverse an array in place?
Use two indexes, one at each end. Swap the elements they point to with a temporary variable, then move both indexes inward, until they meet. That takes length / 2 swaps and no extra array.
Practice
- Easy: Reverse
{'J', 'A', 'V', 'A'}in place and print it. - Harder: Rotate an array right by one:
{1, 2, 3, 4}becomes{4, 1, 2, 3}, in place.
Key Takeaways
Was this tutorial helpful?