Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findLastElement ( int N , vector < int > A ) { int l = A . size ( ) ; int j = 0 ; while ( N > l * ( pow ( 2 , j ) ) ) { N = N - l * pow ( 2 , j ) ; j += 1 ; } int k = 1 ; int r = 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 ) { cout << ( A [ i ] ) ; return ; } } } int main ( ) { int K = 7 ; vector < int > A = { 1 , 2 , 3 } ; findLastElement ( K , A ) ; return 0 ; }