Find the last element after repeatedly removing every second element from either end alternately | Function to find the last element remaining in the array after performing the given operations ; Checks if traversal is from left to right or vice versa ; Store the elements currently present in the array ; Store the distance between 2 consecutive array elements ; Store the first element of the remaining array ; Iterate while elements are greater than 1 ; If left to right turn ; Update head ; Otherwise , check if the remaining elements are odd ; If true , update head ; Eleminate half of the array elements ; Double the steps after each turn ; Alter the turn ; Print the remaining element ; Driver code
function printLastElement ( arr , N ) { var leftTurn = true ; var remainElements = N ; var step = 1 ; var head = 1 ; while ( remainElements > 1 ) { if ( leftTurn ) { head = head + step ; } else { if ( remainElements % 2 == 1 ) head = head + step ; } remainElements = remainElements / 2 ; step = step * 2 ; leftTurn = ! leftTurn ; } document . write ( arr [ head - 1 ] ) ; } var arr = [ 2 , 3 , 5 , 6 ] ; var N = arr . length ; printLastElement ( arr , N ) ;