Definition
- Two-pointer technique – one pointer starts at the left end, one at the right end.
- Swap and step – swap the two elements, then move left pointer right and right pointer left.
- Stop condition – continue while
left < right; when they meet, every element is in its mirrored position. - O(n) time – the loop runs n/2 times, each doing a constant-time swap.
- O(1) space – only one temporary variable is needed for the swap, no second array is allocated.
Rajesh has a printed statement where transactions are listed oldest first, but he wants newest first. He puts one finger on the top line and one on the bottom line, swaps those two lines, then moves both fingers inward by one and swaps again. He keeps going until his fingers meet in the middle. Now the whole statement is reversed without needing a second sheet of paper.
Understanding the Concepts
What is the problem?
Given an array, reverse the order of its elements in place. In a banking context, Rajesh's transaction history is stored oldest first at National Bank of India, but the mobile app needs to display newest first.
How does the two-pointer swap work?
Set left to index 0 and right to the last index. Swap array[left] and array[right], then increment left and decrement right. Continue while left < right.
package com.bank.service;
import java.math.BigDecimal;
import java.util.Arrays;
public class StatementReverser {
public static void reverseInPlace(BigDecimal[] transactions) {
if (transactions == null) {
throw new IllegalArgumentException("Transactions cannot be null");
}
int left = 0;
int right = transactions.length - 1;
while (left < right) {
BigDecimal temp = transactions[left];
transactions[left] = transactions[right];
transactions[right] = temp;
left++;
right--;
}
}
public static void main(String[] args) {
BigDecimal[] txns = {
new BigDecimal("1500.00"),
new BigDecimal("8200.00"),
new BigDecimal("3400.00"),
new BigDecimal("12000.00"),
new BigDecimal("500.00")
};
System.out.println("Before: " + Arrays.toString(txns));
reverseInPlace(txns);
System.out.println("After: " + Arrays.toString(txns));
}
}
Before: [1500.00, 8200.00, 3400.00, 12000.00, 500.00]
After: [500.00, 12000.00, 3400.00, 8200.00, 1500.00]
Why does the middle element stay in place for odd-length arrays?
When the array has an odd number of elements, the two pointers eventually land on the same middle element. The condition left < right stops the loop because left is no longer strictly less than right. The middle element is already in its correct position because the reversal mirrors around it.
Why is in-place reversal preferred?
The naive approach creates a new array and copies elements backwards, which uses O(n) extra space. The in-place approach uses only a single temporary variable for the swap, so it is O(1) extra space. For a mobile app displaying a long statement, the extra memory matters.
What is the time and space complexity?
- Time: O(n) because the loop runs n/2 times, each doing a constant-time swap.
- Space: O(1) because only one temporary variable is used.
What are common mistakes?
The most common mistake is using left <= right instead of left < right. With <=, when the array has an odd length, the middle element would be swapped with itself, which is harmless but wasteful. More dangerously, if the loop continued past the middle, it would swap elements back to their original positions, undoing the reversal.
// Mistake: using <= allows unnecessary self-swap
while (left <= right) { /* middle element swaps with itself */ }
// Correct: strict less-than stops at the middle
while (left < right) { /* clean stop */ }
How is this different from creating a reversed copy?
In-place reversal modifies the caller's array, which is a side effect. A reversed copy creates a new array and leaves the original unchanged. In production I offer both methods and document the difference.
// Reversed copy (does not modify original)
public static BigDecimal[] reversedCopy(BigDecimal[] original) {
BigDecimal[] result = new BigDecimal[original.length];
for (int i = 0; i < original.length; i++) {
result[i] = original[original.length - 1 - i];
}
return result;
}
How does array reversal relate to rotation?
Rotating an array by k positions can be done with three reversals: reverse the whole array, reverse the first k elements, and reverse the remaining elements. This is the reversal-based rotation algorithm, which runs in O(n) time and O(1) space.
// Rotate array right by k positions using three reversals
// Step 1: reverse entire array
// Step 2: reverse first k elements
// Step 3: reverse remaining n-k elements
What should a senior engineer know?
A senior engineer knows that in-place reversal is a building block for many algorithms: rotation, palindrome detection, and the next permutation algorithm all use it as a subroutine. The senior also knows to document mutation clearly in the API, and to provide a non-mutating variant when callers need the original preserved. For thread safety, the in-place version requires external synchronisation if the array is shared across threads.
Visual Overview
txns[]: 1500 8200 3400 12000 500
│ │
left=0 right=4
│ │
Step 1: swap(1500, 500) → [500, 8200, 3400, 12000, 1500]
left=1 right=3
Step 2: swap(8200, 12000) → [500, 12000, 3400, 8200, 1500]
left=2 right=2
Stop: left == right (middle element 3400 stays)
Result: [500, 12000, 3400, 8200, 1500]
Key Takeaway
Reversing an array is a textbook two-pointer problem that I solve in place. I put one pointer at the left end and one at the right end, swap the two elements they point at, then move the left pointer one step right and the right pointer one step left. I keep going while the left pointer is still before the right pointer. When they meet in the middle, the whole array is reversed.
In my banking project at National Bank of India, I used this when displaying statements. The database stores Rajesh's transactions oldest first, but the mobile app needs to show the newest transactions at the top. Rather than issuing a second expensive sorted query or building a whole new array, I reverse the list in place inside the service layer.
The in-place aspect is what I emphasise in an interview, because the naive solution creates a brand new array and copies elements backwards, which doubles the memory. On a phone displaying a long statement that extra memory matters, so the two-pointer swap that needs only one temporary variable is the professional choice.
Remember one sentence: two pointers at both ends, swap and step inward, stop when they meet.
---