Mth element after K Right Rotations of an Array | Java program to implement the above approach ; Function to return Mth element of array after k right rotations ; The array comes to original state after N rotations ; If K is greater or equal to M ; Mth element after k right rotations is ( N - K ) + ( M - 1 ) th element of the array ; Otherwise ; ( M - K - 1 ) th element of the array ; Return the result ; Driver Code
class GFG { static int getFirstElement ( int a [ ] , int N , int K , int M ) { K %= N ; int index ; if ( K >= M ) index = ( N - K ) + ( M - 1 ) ; else index = ( M - K - 1 ) ; int result = a [ index ] ; return result ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = 5 ; int K = 3 , M = 2 ; System . out . println ( getFirstElement ( a , N , K , M ) ) ; } }