Given non-negative integers K, M, and an array arr[] with N elements find the Mth element of the array after K left rotations.
Examples:
Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1
Output: 5
Explanation:
The array after first left rotation a1[ ] = {4, 5, 23, 3}
The array after second left rotation a2[ ] = {5, 23, 3, 4}
1st element after 2 left rotations is 5.
Input: arr[] = {1, 2, 3, 4, 5}, K = 3, M = 2
Output: 5
Explanation:
The array after 3 left rotation has 5 at its second position.
Naive Approach: The idea is to Perform Left rotation operation K times and then find the Mth element of the final array.
Time Complexity: O(N * K)
Auxiliary Space: O(N)
Efficient Approach: To optimize the problem, observe the following points:
- If the array is rotated N times it returns the initial array again.
For example, a[ ] = {1, 2, 3, 4, 5}, K=5 then the array after 5 left rotation a5[ ] = {1, 2, 3, 4, 5}.
Therefore, the elements in the array after Kth rotation is the same as the element at index K%N in the original array.
- The Mth element of the array after K left rotations is
{ (K + M – 1) % N }th
element in the original array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getFirstElement( int a[], int N,
int K, int M)
{
K %= N;
int index = (K + M - 1) % N;
int result = a[index];
return result;
}
int main()
{
int a[] = { 3, 4, 5, 23 };
int N = sizeof (a) / sizeof (a[0]);
int K = 2, M = 1;
cout << getFirstElement(a, N, K, M);
return 0;
}
|
Java
import java.util.*;
class GFG{
public static int getFirstElement( int [] a, int N,
int K, int M)
{
K %= N;
int index = (K + M - 1 ) % N;
int result = a[index];
return result;
}
public static void main(String[] args)
{
int a[] = { 3 , 4 , 5 , 23 };
int N = a.length;
int K = 2 , M = 1 ;
System.out.println(getFirstElement(a, N, K, M));
}
}
|
Python3
def getFirstElement(a, N, K, M):
K % = N
index = (K + M - 1 ) % N
result = a[index]
return result
if __name__ = = '__main__' :
a = [ 3 , 4 , 5 , 23 ]
N = len (a)
K = 2
M = 1
print (getFirstElement(a, N, K, M))
|
C#
using System;
class GFG{
public static int getFirstElement( int [] a, int N,
int K, int M)
{
K %= N;
int index = (K + M - 1) % N;
int result = a[index];
return result;
}
public static void Main( string [] args)
{
int []a = { 3, 4, 5, 23 };
int N = a.Length;
int K = 2, M = 1;
Console.Write(getFirstElement(a, N, K, M));
}
}
|
Javascript
<script>
function getFirstElement(a , N , K , M) {
K %= N;
var index = (K + M - 1) % N;
var result = a[index];
return result;
}
var a = [ 3, 4, 5, 23 ];
var N = a.length;
var K = 2, M = 1;
document.write(getFirstElement(a, N, K, M));
</script>
|
Time complexity: O(1)
Auxiliary Space: O(1)