Reverse an array

Asked atEY
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an array arr of n elements. The task is to reverse the given array. The reversal of array should be inplace.

Input: n=5, arr = [1,2,3,4,5]

Output: [5,4,3,2,1]

Explanation: The reverse of the array [1,2,3,4,5] is [5,4,3,2,1]

Input: n=6, arr = [1,2,1,1,5,1]

Output: [1,5,1,1,2,1]

Explanation: The reverse of the array [1,2,1,1,5,1] is [1,5,1,1,2,1].

Input: n=3, arr = [1,2,1]

1 <= n <= 104 1 <= arr[i] <= 105

cpp

class Solution{
public:
    void reverse(int arr[], int n){
        
    }
};

java

class Solution {
    public void reverse(int[] arr, int n) {
   
    }
}

python

class Solution:
    def reverse(self, arr: list, n: int) -> None:

javascript

class Solution {
    // Function to reverse the array in place
    // The reversal should be done IN-PLACE.
    // Do not return anything from this function.
    reverse(arr, n) {
        // Your code here
    }
}

csharp

public class Solution
{
    public void reverse(int[] arr, int n)
    {
   
    }
}

go

func reverse(arr []int, n int) {

}
Stuck? Show a way to structure it+
  1. 01Set left to zero and right to n-1.
  2. 02Swap the values at both pointers.
  3. 03Move left forward and right backward.
  4. 04Stop when pointers meet or cross.

Reference answer

Then expect these follow-ups

  • How would you reverse a linked list?

    Tests: pointer manipulation

  • How would you reverse only a subarray?

    Tests: index boundaries

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question