Reverse an Array In Place

Problem

Reverse an array in place, without using extra space for another array.

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

Python Solution

def reverse_array(nums):
    left, right = 0, len(nums) - 1
    while left < right:
        nums[left], nums[right] = nums[right], nums[left]
        left += 1
        right -= 1
    return nums

C++ Solution

void reverseArray(vector<int>& nums) {
    int left = 0, right = nums.size() - 1;
    while (left < right) {
        swap(nums[left], nums[right]);
        left++;
        right--;
    }
}

Java Solution

class Solution {
    public void reverseArray(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }
}

Complexity

Time: O(n) — each element is swapped once. Space: O(1) — swaps happen in place, no extra array.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.