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
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++
#include <bits/stdc++.h>
using namespace std;
void findShifts( int A[], int N)
{
int shift[N];
for ( int i = 0; i < N; i++) {
if (i == A[i] - 1)
shift[i] = 0;
else
shift[i]
= (A[i] - 1 - i + N)
% N;
}
for ( int i = 0; i < N; i++)
cout << shift[i] << " " ;
}
int main()
{
int arr[] = { 1, 4, 3, 2, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
findShifts(arr, N);
return 0;
}
|
Java
class GFG{
public static void findShifts( int [] A, int N)
{
int [] shift = new int [N];
for ( int i = 0 ; i < N; i++)
{
if (i == A[i] - 1 )
shift[i] = 0 ;
else
shift[i] = (A[i] - 1 - i + N) % N;
}
for ( int i = 0 ; i < N; i++)
System.out.print(shift[i] + " " );
}
public static void main(String[] args)
{
int arr[] = { 1 , 4 , 3 , 2 , 5 };
int N = arr.length;
findShifts(arr, N);
}
}
|
Python3
def findShifts(A, N):
shift = [ 0 for i in range (N)]
for i in range (N):
if (i = = A[i] - 1 ):
shift[i] = 0
else :
shift[i] = (A[i] - 1 - i + N) % N
for i in range (N):
print (shift[i], end = " " )
if __name__ = = '__main__' :
arr = [ 1 , 4 , 3 , 2 , 5 ]
N = len (arr)
findShifts(arr, N)
|
C#
using System;
class GFG{
public static void findShifts( int [] A, int N)
{
int [] shift = new int [N];
for ( int i = 0; i < N; i++)
{
if (i == A[i] - 1)
shift[i] = 0;
else
shift[i] = (A[i] - 1 - i + N) % N;
}
for ( int i = 0; i < N; i++)
Console.Write(shift[i] + " " );
}
public static void Main(String[] args)
{
int []arr = { 1, 4, 3, 2, 5 };
int N = arr.Length;
findShifts(arr, N);
}
}
|
Javascript
<script>
function findShifts(A, N)
{
let shift = Array.from({length: N}, (_, i) => 0);
for (let i = 0; i < N; i++)
{
if (i == A[i] - 1)
shift[i] = 0;
else
shift[i] = (A[i] - 1 - i + N) % N;
}
for (let i = 0; i < N; i++)
document.write(shift[i] + " " );
}
let arr = [ 1, 4, 3, 2, 5 ];
let N = arr.length;
findShifts(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)