Reverse an array
Pattern: Traversal and in-place tricks
Reverse an array in place with two indexes that start at the ends, swap, and move towards each other.
The problem
You are given an array of between 1 and 100,000 whole numbers. Reverse it in place and return it. For example,
[1, 2, 3, 4, 5] becomes [5, 4, 3, 2, 1].
This problem appears in both sheets. Its main link points to GeeksforGeeks, which this site has not been able to check
automatically. The function name reverseArray and the limits are this guide's own. The recursive version is in
Recursion basics.
Think first
- Where does the first element end up? And the last?
- After swapping those two, what is left to reverse?
- When do you stop, for an odd length and for an even length?
Hints
Brute force, and why it fails
Copy the elements into a new array from back to front. That is O(n) time but O(n) extra memory. The two-index swap does the same work inside the original array with O(1) extra memory.
The key insight
Each swap puts two elements in their final places, so n / 2 swaps reverse the whole array without any second array.
Dry run
nums = [1, 2, 3, 4, 5]. left starts at the first index and right at the last.
The plan
left = 0
right = n - 1
while left < right:
swap nums[left] and nums[right]
left = left + 1
right = right - 1
return nums
Complexity
- Time
O(n)- Space
O(1)
About n / 2 swaps, and only two indexes of extra memory.
Edge cases
- One element:
left = right = 0, and nothing happens. - Even length: after the last swap,
leftpassesrightand the loop stops. - Repeated values swap like any others.
I've built my logic, show the code
Java
class Solution {
public int[] reverseArray(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
return nums;
}
}C++
class Solution {
public:
vector<int> reverseArray(vector<int>& nums) {
int left = 0;
int right = static_cast<int>(nums.size()) - 1;
while (left < right) {
swap(nums[left], nums[right]);
left++;
right--;
}
return nums;
}
};Python
class Solution:
def reverseArray(self, nums):
left, right = 0, len(nums) - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return numsCommon mistakes
- Looping
iover the whole array and swappingnums[i]withnums[n - 1 - i]. The second half swaps everything back. - Using
<=in the loop test. That is harmless for odd lengths, but it is a sign the stopping rule is unclear. - Swapping without a temporary variable and losing a value.