Reverse an array
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+
- 01Set left to zero and right to n-1.
- 02Swap the values at both pointers.
- 03Move left forward and right backward.
- 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.
Consultant(e) Data Security F/H (Paris) F/H
Paris
Manager / Senior Manager - Architecte Solution - Databricks F/H FY27
Paris
Next question