Given an array **arr[] **of size **N **that contains elements from the range [1, N], the task is to calculate the number of right shifts required for each element to reach its respective position if the array was sorted.

Examples:

_Input: __arr[] = {1, 4, 3, 2, 5}, N = 5 _

_Output: __0 2 0 3 0 _

Explanation:

_The sorted array is {1, 2, 3, 4, 5}. _

_4 is at index 1, so right shift 2 times to reach index 3. (1->2->3) _

_2 is at index 3, so right shift 3 times to reach index 1. (3->4->0->1) _

All the other elements are at their respective positions in the sorted array.

_Input: __arr[]={2, 4, 3, 1, 5}, N = 5 _

_Output: __2 1 0 2 0 _

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

**Approach: **

The idea is to calculate the difference between the actual position and the sorted position of each element of the array. As the elements are from 1 to**N, **the sorted position of each element can be determined without sorting the array. The sorted position of each element is given by **(arr[i]-1). **Therefore, the number of right shifts is given by **(arr[i] – 1 – i + N) % N.**

Below is the implementation of the above approach:

• C++

`// C++ Program to implement`

`// the approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function to find the right`

`// shifts required for each`

`// element to reach its sorted`

`// array position in A[]`

`**void**` `findShifts(``**int**` `A[],` `**int**` `N)`

`{`

`// Stores required number of`

`// shifts for each element`

`**int**` `shift[N];`

`**for**` `(``**int**` `i = 0; i < N; i++) {`

`// If the element is`

`// at sorted position`

`**if**` `(i == A[i] - 1)`

`shift[i] = 0;`

`// Otherwise`

`**else**`

`// Calculate right shift`

`shift[i]`

`= (A[i] - 1 - i + N)`

`% N;`

`}`

`// Print the respective shifts`

`**for**` `(``**int**` `i = 0; i < N; i++)`

`cout << shift[i] <<` `" "``;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `arr[] = { 1, 4, 3, 2, 5 };`

`**int**` `N =` `**sizeof**``(arr) /` `**sizeof**``(arr[0]);`

`findShifts(arr, N);`

`**return**` `0;`

`}`

Output:

``````0 2 0 3 0

``````

_Time Complexity: __O(N) _

_Auxiliary Space: _O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #array-rearrange

1.10 GEEK