Reverse Array in Java: Solution, Explanation & Practice
Reverse an array in place
Problem summary
Write a program that reverses an array. Your code should work for ANY array.
Starter code
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5}; // Test case 1
// Reverse array in place
// Print elements space-separated
}
}Expected output and test cases
- Reverse [1,2,3,4,5]
5 4 3 2 1
- Reverse [1,2,3,4]
4 3 2 1
- Reverse [1]
1
Hints
- Swap elements from both ends
- Use two pointers: start and end
- Stop when pointers meet in middle
Validated solution
Reveal Java solution
import java.util.Arrays;
public class Main {
static void reverse(int[] values) {
for (int left = 0, right = values.length - 1; left < right; left++, right--) {
int temporary = values[left];
values[left] = values[right];
values[right] = temporary;
}
}
public static void main(String[] args) {
int[] values = {1, 2, 3, 4, 5};
reverse(values);
System.out.println(Arrays.toString(values).replace("[", "").replace("]", "").replace(",", ""));
}
}How to approach the problem
Two pointers identify the next unmatched values at the front and back. Swapping them and moving both inward preserves the already reversed outer portion without allocating another array.
Approach
- Set left to 0 and right to length - 1.
- Swap while left is strictly before right.
- Move both pointers inward after each swap.
Time and space complexity
Time: O(n). Space: O(1).
Edge cases to test
- Empty and single-element arrays need no swap.
- The method mutates the supplied array; callers that need the original should copy first.
Common mistakes
- Using left <= right and performing an unnecessary middle self-swap.
- Updating one pointer but not the other.
Follow-up challenge
Reverse only a requested inclusive range and validate its bounds.
Related Arrays exercises
- Practice Count Even Numbers in Java
- Practice Linear Search in Java
- Practice Second Largest Element in Java
Practice all Arrays exercises · Run this idea in the Java compiler