Last Updated: June 7, 2026
Flip the order of the elements so the last one becomes first, the second-to-last becomes second, and so on. The phrase "in place" is the constraint that matters: you cannot build a fresh array and copy values into it. You must rearrange the existing array using only a constant amount of extra space.
A few cases keep the logic honest. An empty array reverses to an empty array. A single-element array stays the same because there is nothing to swap. Arrays with negative numbers reverse the same way as any other, since reversing cares about position, not value.
0 <= nums.length <= 10^4 → The array can be empty. Your loop must handle a length of 0 without touching any elements, and it must finish quickly even at the upper size.Copying elements into a new array from back to front works, but it costs O(n) extra space for the second full-size array, which the constraint forbids.
Instead, swap pairs from the outside in. Place one pointer at the start and another at the end. The two values they point to need to trade places in the final result, so swap them. Then move the left pointer one step right and the right pointer one step left, and repeat. Each swap fixes two elements into their final positions at once, so the pointers only travel until they meet in the middle.
The only memory this needs is the two indices and one temporary variable used during each swap, which is O(1) extra space.
left = 0 and right = nums.length - 1.left < right, swap nums[left] and nums[right].left and decrement right.nums.Input:
Start with left = 0 and right = 4. The values there are 1 and 5, so swap them. The array becomes [5, 2, 3, 4, 1]. Move the pointers inward to left = 1 and right = 3. The values there are 2 and 4, so swap them. The array becomes [5, 4, 3, 2, 1]. Move inward again to left = 2 and right = 2. The pointers now point at the same middle element, so the condition left < right is false and the loop stops. The element at index 2 never needed to move because it sits exactly in the center.