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

Hiring now

EY is hiring right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Consultant(e) Data Security F/H (Paris) F/H

    Paris

  • Manager / Senior Manager - Architecte Solution - Databricks F/H FY27

    Paris

Or practice this question first

Next question