Reverse an Array

Solve this Problem
Easy5–10 min
Topics
Companies
Practice:GFG ↗
Given an array of integers nums, reverse the array in-placeIn-PlaceModifying the original data directly, without allocating a separate array or data structure to hold the result. Uses only O(1) extra space. and return it. Do not use a second array for the optimal solution — swap elements directly within nums using two pointers moving toward each other from opposite ends.

Test Case 1:

Input:nums = [1, 2, 3, 4, 5]
Output:[5, 4, 3, 2, 1]
Explanation:The first and last elements swap, then the second and second-last, and so on.

Test Case 2:

Input:nums = [1, 2]
Output:[2, 1]
Explanation:Only one swap needed for a 2-element array.

Test Case 3:

Input:nums = [7]
Output:[7]
Explanation:A single element is already its own reverse.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • Reverse the array in-place — do not allocate a second array for the optimal solution
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

🧪Try your own test case
1class Solution {
2 public int[] reverseArray(int[] nums) {
3 int left = 0;
4 int right = nums.length - 1;
5 while (left < right) {
6 int temp = nums[left];
7 nums[left] = nums[right];
8 nums[right] = temp;
9 left++;
10 right--;
11 }
12 return nums;
13 }
14}
15
1
2
3
4
5
0
1
2
3
4
left
right
Variables
left0
right4
INITIALIZE

Place left at the very start and right at the very end. They'll walk toward each other.

Step 1 / 8

Approach & Solutions

Brute Force — Extra Array

Brute

Create a new array of the same size. Walk through the original array from the end to the start, copying each element into the new array in order. Return the new array. Correct, but uses extra memory the optimal approach doesn't need.

TimeO(n)
SpaceO(n)
1class Solution { 2 public int[] reverseArray(int[] nums) { 3 int[] result = new int[nums.length]; 4 for (int i = 0; i < nums.length; i++) { 5 result[i] = nums[nums.length - 1 - i]; 6 } 7 return result; 8 } 9}

Optimal — Two Pointer Swap (In-Place)

Optimal

Place one pointer at the start (left) and one at the end (right). Swap the elements they point to, then move left forward and right backward. Stop once they meet or cross. No extra array needed — the original array is reversed directly.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int[] reverseArray(int[] nums) { 3 int left = 0; 4 int right = nums.length - 1; 5 while (left < right) { 6 int temp = nums[left]; 7 nums[left] = nums[right]; 8 nums[right] = temp; 9 left++; 10 right--; 11 } 12 return nums; 13 } 14}

Related Problems