Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times | Java program for the above approach ; Function to find the last element after performing given operations ; Length of the array ; Increment j until condition is satisfied ; In each pair every value is repeating r number of times ; Print the result according to the value of k ; Driver Code ; Given K ; Given arr [ ] ; Function call
import java . io . * ; class GFG { static void findLastElement ( int N , int [ ] A ) { int l = A . length ; int j = 0 ; while ( N > l * ( int ) ( Math . pow ( 2 , j ) ) ) { N = N - l * ( int ) Math . pow ( 2 , j ) ; j += 1 ; } int k = 1 ; int r = ( int ) Math . pow ( 2 , j ) ; for ( int i = 1 ; i < l ; i ++ ) { if ( N > r * i ) k += 1 ; } for ( int i = 0 ; i < l ; i ++ ) { if ( i + 1 == k ) { System . out . print ( A [ i ] ) ; return ; } } } public static void main ( String [ ] args ) { int K = 7 ; int [ ] A = { 1 , 2 , 3 } ; findLastElement ( K , A ) ; } }