Fundamentals · Easy · Free
Reverse an array in-place. What is the time and space complexity?
FresherFundamentalsData Structures & Algorithms
Reverse in-place
Swap elements from both ends moving inward—O(n) time, O(1) extra space.
java
void reverse(int[] a) {
int l = 0, r = a.length - 1;
while (l < r) {
int tmp = a[l]; a[l] = a[r]; a[r] = tmp;
l++; r--;
}
}Works for strings via
char[] or two-pointer swap.