Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times | 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 ; Given K ; Given arr [ ] ; Function call
function findLastElement ( N , A ) { let l = A . length ; let j = 0 ; while ( N > l * ( Math . pow ( 2 , j ) ) ) { N = N - l * Math . pow ( 2 , j ) ; j += 1 ; } let k = 1 ; let r = Math . pow ( 2 , j ) ; for ( let i = 1 ; i < l ; i ++ ) { if ( N > r * i ) k += 1 ; } for ( let i = 0 ; i < l ; i ++ ) { if ( i + 1 == k ) { document . write ( A [ i ] ) ; return ; } } } let K = 7 ; let A = [ 1 , 2 , 3 ] ; findLastElement ( K , A ) ;