In this Leetcode Elimination Game, problem solution you have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:

Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.

Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.

Keep repeating the steps again, alternating left to right and right to left, until a single number remains. we have given the integer n, return the last number that remains in arr.

Leetcode Elimination Game problem solution


Problem solution in Python.

def lastRemaining(self, n: int) -> int:
    if n < 3: return n
    if n == 3: return 2
    temp = n & 3  # n % 4
    if temp == 0:
        return (self.lastRemaining(n>>2) << 2) - 2  # 4 * lr(n/4) - 2
    elif temp == 2:
        return self.lastRemaining(n>>2) << 2  # 4 * lr(n/4)
    else:
        return self.lastRemaining(n-1)



Problem solution in Java.

public int lastRemaining(int n) {
        if (n == 1) {
            return 1;
        } else if (n % 2 == 1) {
            return lastRemaining(n - 1);
        } else {
            return (n + 2 - 2 * lastRemaining(n / 2));
        }
    }


Problem solution in C++.

class Solution {
public:
    int lastRemaining(int n, bool left=true) {
        if(n==1) return 1;
        return 2 * lastRemaining(n/2, !left) + (left?0:n%2-1);
    }
};


Problem solution in C.

int func(int n, int flag){
    if(n==1){
        return 1;
    }
    if(n<5&&flag!=0){
        return 2;
    }
    if(flag==0){
        if(n%2==0){
            return 2*func(n/2,!flag)-1;
        }
    }
    return 2*func(n/2,!flag);
}
int lastRemaining(int n) {
    if(n==1){
        return 1;
    }
    if(n<5){
        return 2;
    }
    return 2*func((n%2==0?n:n-1)/2,0);
}