Back to ArraysReverse an Array
Easy

Reverse an Array

EasyOptionalBasic Traversal

Given an array, reverse it in place so the last element becomes the first, using only constant extra space.

Examples

Example 1

Input:
nums = [1,2,3,4,5]
Output:
[5,4,3,2,1]

Explanation: Each element swaps with its mirror position: index 0 with 4, index 1 with 3; the middle element stays put.

Example 2

Input:
nums = [1,2,3,4]
Output:
[4,3,2,1]

Explanation: With an even length, every element has a distinct mirror partner.

Example 3

Input:
nums = [7]
Output:
[7]

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • Must be done in place with O(1) extra space.

Loading editor…

Code execution is coming soon.