Reverse an Array
Java coding interview problem for Array Coding: Reverse an Array.
Reversing an array is one of the most fundamental array manipulation problems in Java.
This problem looks simple, but it helps you understand important concepts:
- Array Indexing
- Swapping Elements
- Two Pointer Technique
- Recursion
- In-place Algorithms
- Time Complexity
- Space Complexity
Array reversal is the foundation for many advanced interview problems:
- Reverse a String
- Rotate an Array
- Reverse Linked List
- Palindrome Checking
- Two Pointer Problems
- Data Transformation
What Does Reversing an Array Mean?
Reversing an array means changing the order of elements so that:
- The first element becomes the last.
- The second element becomes the second last.
- The last element becomes the first.
Example
Input:
[10,20,30,40,50]
After reversing:
[50,40,30,20,10]
Another Example:
Input:
[1,2,3,4]
Output:
[4,3,2,1]
Why is This Question Asked in Interviews?
Interviewers ask array reversal because it evaluates your understanding of:
- Index manipulation
- Swapping logic
- Memory usage
- Loop control
- Recursive thinking
It is also used as a building block for:
- Array rotation
- String reversal
- Linked list reversal
- Partition algorithms
Real-World Applications
Array reversal concepts are used in many systems.
Data Processing
Reverse chronological data:
Before:
[Oldest, ..., Newest]
After:
[Newest, ..., Oldest]
User Interfaces
Displaying recent items first:
Example:
Old Messages
↓
New Messages
Undo Operations
Applications often reverse operation sequences.
Example:
Operation 1
Operation 2
Operation 3
Undo order:
Operation 3
Operation 2
Operation 1
Image Processing
Pixel arrays may be reversed for:
- Mirroring
- Flipping
- Transformations
Algorithms
Many algorithms use reversal internally:
- Array Rotation
- Next Permutation
- Backtracking
Problem Statement
Given an integer array,
reverse the order of elements.
Example 1
Input:
[1,2,3,4,5]
Output:
[5,4,3,2,1]
Example 2
Input:
[10,20,30]
Output:
[30,20,10]
Example 3
Input:
[7]
Output:
[7]
Example 4
Input:
[]
Output:
[]
Understanding Array Reversal
Consider:
[10,20,30,40,50]
We need to swap:
First and last:
10 ↔ 50
Second and second last:
20 ↔ 40
Middle element remains unchanged.
Final:
[50,40,30,20,10]
Mathematical Concept
For an array of size n:
Original index:
i
New index:
n - 1 - i
Example:
Array:
[10,20,30,40,50]
Length:
n = 5
Element:
10
Index:
0
New position:
5 - 1 - 0
Result:
4
So:
10 moves to index 4
Array Visualization
Input:
Index:
0 1 2 3 4
10 20 30 40 50
Reverse:
0 ↔ 4
1 ↔ 3
2 stays
Result:
50 40 30 20 10
Dry Run
Input:
[5,10,15,20,25]
Initial:
left = 0
right = 4
Swap:
5 ↔ 25
Array:
[25,10,15,20,5]
Move pointers:
left++
right--
Swap:
10 ↔ 20
Array:
[25,20,15,10,5]
Stop:
left >= right
Final:
[25,20,15,10,5]
Approach 1 — Using Extra Array (Beginner Friendly)
The simplest approach is creating a new array.
The idea:
- Traverse original array.
- Store elements in reverse positions.
Algorithm
- Create a new array of same size.
- Traverse original array.
- Copy element to reverse index.
- Return new array.
Java Program
import java.util.Arrays;
public class ReverseArrayExtraSpace {
public static int[] reverse(int[] numbers) {
int n = numbers.length;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[n - 1 - i] = numbers[i];
}
return result;
}
public static void main(String[] args) {
int[] numbers =
{10,20,30,40,50};
System.out.println(
Arrays.toString(
reverse(numbers)));
}
}
Output
[50, 40, 30, 20, 10]
Step-by-Step Explanation
Original array:
[10,20,30,40,50]
Length:
5
Element:
10
Index:
0
New position:
5 - 1 - 0
Result:
4
Place:
result[4] = 10
Element:
20
New index:
3
Final:
[50,40,30,20,10]
Complexity Analysis
Time:
O(n)
Every element is visited once.
Space:
O(n)
A new array is created.
Advantages
- Easy to understand.
- Beginner friendly.
- Does not modify original array.
- Simple implementation.
Drawbacks
- Requires additional memory.
- Not suitable for memory-sensitive applications.
Approach 2 — Two Pointer Approach (Optimal)
The two pointer technique is the most recommended interview solution.
Instead of creating a new array,
we swap elements inside the same array.
Two Pointer Concept
Use two indexes:
left
right
Initially:
left = 0
right = n - 1
Swap:
numbers[left]
with
numbers[right]
Move:
left++
right--
Continue until:
left >= right
Example
Input:
[1,2,3,4,5]
Pointers:
L R
1 2 3 4 5
Swap:
5 2 3 4 1
Move:
L R
Swap:
5 4 3 2 1
Done.
Java Program
import java.util.Arrays;
public class ReverseArrayTwoPointer {
public static void reverse(int[] numbers) {
int left = 0;
int right = numbers.length - 1;
while (left < right) {
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
left++;
right--;
}
}
public static void main(String[] args) {
int[] numbers =
{1,2,3,4,5};
reverse(numbers);
System.out.println(
Arrays.toString(numbers));
}
}
Output
[5,4,3,2,1]
Step-by-Step Code Explanation
Initialize pointers:
int left = 0;
int right = numbers.length - 1;
Swap values:
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
Move pointers:
left++;
right--;
Continue until:
left >= right
Dry Run
Input:
[1,2,3,4,5]
Initial:
left = 0
right = 4
Swap:
1 ↔ 5
Array:
[5,2,3,4,1]
Swap:
2 ↔ 4
Array:
[5,4,3,2,1]
Stop.
Result:
[5,4,3,2,1]
Complexity Analysis
Time:
O(n)
Space:
O(1)
Advantages
- Optimal solution.
- In-place reversal.
- No extra memory.
- Preferred interview approach.
Drawbacks
- Modifies original array.
- Requires understanding swap logic.
Approach 3 — Using Recursion
Recursion is another way to reverse an array.
The idea is similar to the two pointer approach:
- Swap the first and last elements.
- Move towards the center.
- Repeat recursively.
Recursive Concept
Example:
Input:
[10,20,30,40,50]
First call:
Swap:
10 ↔ 50
Array:
[50,20,30,40,10]
Recursive call:
Reverse remaining:
20 ↔ 40
Array:
[50,40,30,20,10]
Stop when:
left >= right
Algorithm
-
Start with two indexes:
- left = 0
- right = array length - 1
-
Swap elements.
-
Call the function recursively with:
left + 1
right - 1
- Stop when pointers meet.
Java Program
import java.util.Arrays;
public class ReverseArrayRecursion {
public static void reverse(
int[] numbers,
int left,
int right) {
if (left >= right) {
return;
}
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
reverse(
numbers,
left + 1,
right - 1);
}
public static void main(String[] args) {
int[] numbers =
{10,20,30,40,50};
reverse(
numbers,
0,
numbers.length - 1);
System.out.println(
Arrays.toString(numbers));
}
}
Output
[50,40,30,20,10]
Step-by-Step Explanation
Initial call:
reverse(numbers,0,4)
Swap:
10 ↔ 50
Array:
[50,20,30,40,10]
Recursive call:
reverse(numbers,1,3)
Swap:
20 ↔ 40
Array:
[50,40,30,20,10]
Recursive call:
reverse(numbers,2,2)
Condition:
left >= right
Stop.
Complexity Analysis
Time:
O(n)
Each element is processed once.
Space:
O(n)
because recursive calls use the call stack.
Advantages
- Simple recursive logic.
- Good for understanding recursion.
- Useful for recursive problem practice.
Drawbacks
- Uses stack memory.
- Possible StackOverflowError for very large arrays.
- Less preferred than iterative two pointer solution.
Approach 4 — Using Collections.reverse()
Java Collections Framework provides:
Collections.reverse()
which reverses a List in-place.
Algorithm
- Convert array into List.
- Call
Collections.reverse(). - Convert back if required.
Java Program
import java.util.*;
public class ReverseArrayCollections {
public static void main(String[] args) {
Integer[] numbers =
{10,20,30,40,50};
List<Integer> list =
Arrays.asList(numbers);
Collections.reverse(list);
System.out.println(list);
}
}
Output
[50,40,30,20,10]
Step-by-Step Explanation
Original:
[10,20,30,40,50]
Convert:
Arrays.asList(numbers)
Creates:
List
Reverse:
Collections.reverse(list)
Result:
[50,40,30,20,10]
Advantages
- Very readable.
- Uses Java built-in API.
- Less chance of implementation errors.
Drawbacks
- Works with objects, not primitive arrays directly.
- Requires boxing for
int[]. - Not ideal for algorithm interviews.
Approach 5 — Using Java Streams
Java Streams can reverse an array by:
- Converting indexes.
- Mapping elements in reverse order.
- Creating a new array.
Java Program
import java.util.Arrays;
import java.util.stream.IntStream;
public class ReverseArrayStreams {
public static int[] reverse(int[] numbers) {
return IntStream.range(0, numbers.length)
.map(i -> numbers[numbers.length - 1 - i])
.toArray();
}
public static void main(String[] args) {
int[] numbers =
{10,20,30,40,50};
System.out.println(
Arrays.toString(
reverse(numbers)));
}
}
Output
[50,40,30,20,10]
Step-by-Step Explanation
Original:
Index:
0 1 2 3 4
10 20 30 40 50
Stream generates indexes:
0 1 2 3 4
Mapping:
numbers[length - 1 - i]
Creates:
50 40 30 20 10
Advantages
- Functional programming style.
- Concise implementation.
- Useful in stream-based processing.
Drawbacks
- Creates a new array.
- Less memory efficient.
- Overkill for simple reversal.
In-Place vs Extra Space Reversal
| Approach | In-Place | Extra Memory |
|---|---|---|
| Two Pointer | ✅ | O(1) |
| Cyclic Replacement | ✅ | O(1) |
| Recursion | ✅ | O(n) Stack |
| Extra Array | ❌ | O(n) |
| Streams | ❌ | O(n) |
Primitive vs Object Arrays
Primitive Array
Example:
int[] numbers;
Advantages:
- Faster execution.
- Less memory.
- No boxing overhead.
Object Array
Example:
Integer[] numbers;
Advantages:
- Works with Collections.
- Supports Java Generics.
Comparison of All Approaches
| Approach | Time Complexity | Space Complexity | Interview Rating |
|---|---|---|---|
| Extra Array | O(n) | O(n) | ⭐⭐⭐ |
| Two Pointer | O(n) | O(1) | ⭐⭐⭐⭐⭐ |
| Recursion | O(n) | O(n) | ⭐⭐⭐⭐ |
| Collections.reverse() | O(n) | O(1)* | ⭐⭐⭐ |
| Streams | O(n) | O(n) | ⭐⭐⭐ |
*For existing List implementation.
Common Interview Mistakes
Mistake 1
Using extra memory when asked for in-place reversal.
Example:
int[] result = new int[n];
Better:
Two Pointer
Mistake 2
Incorrect swap logic.
Wrong:
numbers[left] = numbers[right];
numbers[right] = numbers[left];
Correct:
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
Mistake 3
Wrong loop condition.
Correct:
while(left < right)
Wrong:
while(left <= right)
Mistake 4
Ignoring empty arrays.
Example:
[]
Should return:
[]
Mistake 5
Confusing reverse with sorting.
Reverse:
[5,1,4,2]
becomes:
[2,4,1,5]
Sorting:
[1,2,4,5]
They are different operations.
Edge Cases
| Input | Output |
|---|---|
[] |
[] |
[1] |
[1] |
[1,2] |
[2,1] |
[5,5,5] |
[5,5,5] |
| Negative numbers | Works correctly |
Interview Follow-up Questions
Q1. Reverse an array without extra space.
Q2. Reverse an array recursively.
Q3. Reverse only a part of an array.
Q4. Reverse an array of strings.
Q5. Reverse a linked list.
Q6. Reverse words in a sentence.
Q7. Rotate an array using reversal.
Q8. Find palindrome using reverse logic.
Q9. Reverse an array in Java Streams.
Q10. Reverse an array larger than memory.
Related Problems
- Reverse String
- Reverse Words in String
- Rotate Array
- Palindrome Check
- Reverse Linked List
- Swap Elements
- Two Pointer Problems
- Next Permutation
Key Takeaways
- Array reversal is a fundamental DSA problem.
- Two Pointer is the optimal interview solution.
Remember:
left pointer
+
right pointer
↓
swap
↓
move inward
Complexity:
Time: O(n)
Space: O(1)
- Extra Array is easier but uses more memory.
- Recursion demonstrates algorithmic thinking.
- Collections and Streams provide convenient Java solutions.
Frequently Asked Interview Questions
Q1. Which approach is best?
The two pointer approach.
Complexity:
Time: O(n)
Space: O(1)
Q2. Why use two pointers?
Because each pair of elements can be swapped from both ends, reducing unnecessary operations.
Q3. Why stop when left reaches right?
Because all elements have already been swapped.
Q4. Can reversal be done without modifying the original array?
Yes.
Use:
- Extra Array
- Streams
Q5. Which approach is preferred in production?
Depends on requirements:
- Performance critical → Two Pointer
- Immutable data → New Array
- Readability → Collections.reverse()
Interview Tip
When asked:
"Reverse an array."
Start with:
Two Pointer Approach
Explain:
- Initialize left and right indexes.
- Swap values.
- Move pointers inward.
- Stop when they meet.
Then discuss alternatives:
- Extra Array
- Two Pointer (Optimal)
- Recursion
- Collections.reverse()
- Streams
Understanding the trade-offs between memory, readability, and performance demonstrates strong Java and algorithm knowledge.