Find the Mth element of the Array after K left rotations | C ++ program for the above approach ; Function to return Mth element of array after k left rotations ; The array comes to original state after N rotations ; Mth element after k left rotations is ( K + M - 1 ) % N th element of the original array ; Return the result ; Driver Code ; Array initialization ; Size of the array ; Given K rotation and Mth element to be found after K rotation ; Function call
#include <bits/stdc++.h> NEW_LINE 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 ; }