Array Reversal - Problem

Given an array of integers, reverse the array in-place without using any additional array or extra space.

The reversal should be done by modifying the original array directly, swapping elements from both ends moving towards the center.

For example, if the input array is [1, 2, 3, 4, 5], the output should be [5, 4, 3, 2, 1].

Constraints:

  • You must reverse the array in-place (O(1) extra space)
  • Do not create a new array
  • Handle edge cases like empty arrays and single elements

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4,5]
Output: [5,4,3,2,1]
💡 Note: Reverse the array in-place: first element becomes last, last becomes first, and so on
Example 2 — Even Length Array
$ Input: nums = [1,2,3,4]
Output: [4,3,2,1]
💡 Note: With even length, pointers meet exactly in the middle after swapping all pairs
Example 3 — Single Element
$ Input: nums = [42]
Output: [42]
💡 Note: Single element array remains unchanged - pointers start equal so no swaps needed

Constraints

  • 1 ≤ nums.length ≤ 105
  • -231 ≤ nums[i] ≤ 231 - 1

Visualization

Tap to expand
INPUT ARRAYALGORITHM STEPSFINAL RESULT12345Original: [1,2,3,4,5]1Initialize left=0, right=42Swap nums[0] ↔ nums[4]3Move left++, right--4Repeat until left >= right54321Reversed: [5,4,3,2,1]Key Insight:Two pointers from opposite ends eliminate the need for extra spaceby swapping elements in-place while moving toward the center.TutorialsPoint - Array Reversal | Two Pointers Approach
Asked in
Microsoft 25 Amazon 20 Google 15 Apple 12
30.6K Views
High Frequency
~8 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen