Reduce the given Array of [ 1 , N ] by rotating left or right based on given conditions | Function to find the last element left after performing N - 1 queries of type X ; Stores the next power of 2 ; Iterate until nextPower is at most N ; If X is equal to 1 ; Stores the power of 2 less than or equal to N ; Return the final value ; Driver Code
function rotate ( arr , N , X ) { let nextPower = 1 ; while ( nextPower <= N ) nextPower *= 2 ; if ( X == 1 ) return nextPower - N ; let prevPower = nextPower / 2 ; return 2 * ( N - prevPower ) + 1 ; } let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let X = 1 ; let N = arr . length ; document . write ( rotate ( arr , N , X ) ) ;