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
def printLastElement ( arr , N ) : NEW_LINE INDENT leftTurn = True NEW_LINE remainElements = N NEW_LINE step = 1 NEW_LINE head = 1 NEW_LINE while ( remainElements > 1 ) : NEW_LINE INDENT if ( leftTurn ) : NEW_LINE INDENT head = head + step NEW_LINE DEDENT else : NEW_LINE INDENT if ( remainElements % 2 == 1 ) : NEW_LINE INDENT head = head + step NEW_LINE DEDENT DEDENT remainElements = remainElements // 2 NEW_LINE step = step * 2 NEW_LINE leftTurn = not leftTurn NEW_LINE DEDENT print ( arr [ head - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE printLastElement ( arr , N ) NEW_LINE DEDENT