Last element remaining after repeated removal of Array elements at perfect square indices | Function to find last remaining index after repeated removal of perfect square indices ; Initialize the ans variable as N ; Iterate a while loop and discard the possible values ; Total discarded values ; Check if this forms a perfect square ; Decrease answer by 1 ; Subtract the value from the current value of N ; Return the value remained ; Function to find last remaining element after repeated removal of array element at perfect square indices ; Find the remaining index ; Print the element at that index as the result ; Given input
function findRemainingIndex ( N ) { let ans = N ; while ( N > 1 ) { let discard = Math . floor ( Math . sqrt ( N ) ) ; if ( discard * discard == N ) { ans -- ; } N -= discard ; } return ans ; } function findRemainingElement ( arr , N ) { let remainingIndex = findRemainingIndex ( N ) ; document . write ( arr [ remainingIndex - 1 ] ) ; } let arr = [ 2 , 3 , 4 , 4 , 2 , 4 , - 3 , 1 , 1 ] ; let N = arr . length ; findRemainingElement ( arr , N ) ;