Reverse an Integer Array In Place with Constant Extra Memory

Quick Overview

Reverse the elements of an integer array in place and return the same array, using only constant extra memory. It tests basic array index arithmetic, correct loop termination for odd and even lengths, and time and space complexity analysis.

Reverse an Integer Array In Place with Constant Extra Memory

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

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 ```python 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 ```text 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. ```text 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. ```text Input: nums = [42] Output: [42] ``` A single element is already its own reverse, so the array comes back unchanged.

Overview: Reverse the elements of an integer array in place and return the same array, using only constant extra memory. It tests basic array index arithmetic, correct loop termination for odd and even lengths, and time and space complexity analysis.

Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

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.