# Reverse The Array

Posted: 16 Mar, 2021

Difficulty: Easy

#### Given an array/list 'ARR' of integers and a position ‘M’. You have to reverse the array after that position.

#### Example:

```
We have an array ARR = {1, 2, 3, 4, 5, 6} and M = 3 , considering 0
based indexing so the subarray {5, 6} will be reversed and our
output array will be {1, 2, 3, 4, 6, 5}.
```

##### Input format:

```
The very first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of every test case contains one integer ‘N’ where ‘N’ denotes the number of elements and an integer ‘M’ which denotes after which position the array has to be reversed.
The second line of every test case contains ‘N’ space-separated integers which denote the elements of input of array/list.
```

##### Output format:

```
For each test case, return the required array.
Output for each test case is printed on a separate line.
```

##### Note:

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
Consider 0-based indexing of the array.
```

##### Constraints:

```
1 <= T <= 10
0 <= M <= N <= 5*10^4
-10^9 <= ARR[i] <= 10^9
Time Limit: 1 sec
```

Approach 1

**Approach:**

- Here we will use another array for reversing the elements.
- The basic idea is just to store the elements up to the Mth position in the newly created array in the same way as they are given in the original array. Now after the Mth position store the elements in the reverse order.

**Algorithm:**

- Firstly we will create another array say ‘BRR’ of the same size as the original array.
- We will take one variable P = 0.
- Now run a for loop in the forward direction from i=0 to i=M and fill the array ‘BRR’ in the same way as the original array i.e BRR[P++] = ARR[i]. Here ‘i’ will be incremented by one in each iteration.
- Now run a second for loop in the reverse direction from j=N-1 to j=k+1 and fill the array ‘BRR’.Now the elements will be filled in the reversed order i.e BRR[p++] = ARR[j]. Here ‘j’ will be decremented by one in each iteration.
- Finally copy back the array ‘BRR’ to array ‘ARR’ which the required array we want.

Approach 2

**Approach:**

- The basic idea is just to take two pointers, one pointing to the index i = M+1 and another pointer pointing to index j=N-1. Now till the condition i<j holds, swap the elements.

**Algorithm:**

- Firstly take two pointers ‘i’ and ‘j’.
- i = M+1 and j = N-1.
- Now run a while loop with a condition i<j. Inside the while loop:
- swap ARR[i] and ARR[j].
- And after swapping, increment ‘i’ by one and decrement ‘j’ by one.

- This is the required array we want.

SIMILAR PROBLEMS

# Two Sum II - Input Array Is Sorted

Posted: 4 Mar, 2022

Difficulty: Moderate

# Ninja And Matrix

Posted: 12 Apr, 2022

Difficulty: Easy

# Ninja In Interview

Posted: 13 Apr, 2022

Difficulty: Easy

# Missing Number

Posted: 17 Apr, 2022

Difficulty: Easy

# Min Heap

Posted: 5 May, 2022

Difficulty: Moderate