Find the last element after repeatedly removing every second element from either end alternately | Java program for the above approach ; 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
import java . lang . * ; class GFG { public static void printLastElement ( int arr [ ] , int N ) { boolean leftTurn = true ; int remainElements = N ; int step = 1 ; int 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 ; } System . out . print ( arr [ head - 1 ] ) ; } public static void main ( String args [ ] ) { int [ ] arr = { 2 , 3 , 5 , 6 } ; int N = arr . length ; printLastElement ( arr , N ) ; } }