Given an integer array nums, reverse the elements of the array in place and return the reversed array.
You must do this by modifying the input array directly with O(1) extra memory.
Function Signature
def reverse_array(nums: list[int]) -> list[int]:
Rules
-
Rearrange the elements of
nums
itself and return that same list. Do not build and return a separate reversed copy.
-
After the call, position
i
holds the value that was at position
len(nums) - 1 - i
before the call.
-
Values may repeat and may be negative. They are moved, never changed.
Constraints
-
1 <= len(nums) <= 10^4
-
-10^4 <= nums[i] <= 10^4
Examples
Input: nums = [1,2,3,4,5]
Output: [5,4,3,2,1]
The first and last elements swap, the second and fourth swap, and the middle element stays in place.
Input: nums = [3,-1,0,7]
Output: [7,0,-1,3]
With an even length there is no middle element, so each pair of elements from opposite ends is swapped.
Input: nums = [42]
Output: [42]
A single element is already its own reverse, so the array comes back unchanged.