Data Structures

Reverse Array

Array

Given an array arr, reverse the array.

You should solve this problem in-place, without creating a new Array.

First Few Test Cases:
reverseArray([1, 2, 3])
# [3, 2, 1]
reverseArray([1, 2, 2, 3])
# [3, 2, 2, 1]
reverseArray([1, 3, 2])
# [2, 3, 1]

You need to solve this problem in-place, without creating a new Array. The idea for reversing the array is to swap all the elements in pairs, like this:

Reverse Array - image

When you you're done, you'll end up with the reversed array, like this:

Reverse Array - image

To do this, you can use 2 pointers, one starting at the right side of the array n-1, and one starting at the left side 0.

Reverse Array - image

You keep moving the pointers inwards and swapping elements, until each element has been swapped with the element on the opposite side. You stop when the pointers cross each other. Here's the code for this:

def reverseArray(arr):
    n = len(arr)

    l = 0 # left pointer
    r = n-1 # right pointer

    while l < r: # while the pointers haven't crossed each other

        arr[l], arr[r] = arr[r], arr[l] # swap elements

        l = l + 1 # move left pointer forwards
        r = r - 1 # move right pointer backwards

Time Complexity O(n)O(n). We loop through the entire array.

Space Complexity O(1)O(1). We don't have to store any variables. The size of the input never counts towards the space complexity, which is why the space complexity is O(1) and not O(n).

Mark as Completed:
Submits:
reverseArray
Test your code to get an output here!
reverseArray(
)
Test your code to get an output here!