Elimination Game

medium math simulation

Problem

Numbers 1..n in order. Repeatedly remove every other starting from the first; then from the last to the first; alternate until only one remains. Return that number.

Inputn = 9
Output6
After two passes: [2,4,6,8]; right-to-left strip leaves [2,6]; final left-to-right pass leaves [6].

def last_remaining(n):
    head = 1
    step = 1
    left = True
    while n > 1:
        if left or n % 2 == 1:
            head += step
        n //= 2
        step *= 2
        left = not left
    return head
function lastRemaining(n) {
  let head = 1, step = 1, left = true;
  while (n > 1) {
    if (left || n % 2 === 1) head += step;
    n = Math.floor(n / 2);
    step *= 2;
    left = !left;
  }
  return head;
}
class Solution {
    public int lastRemaining(int n) {
        int head = 1, step = 1; boolean left = true;
        while (n > 1) {
            if (left || n % 2 == 1) head += step;
            n /= 2;
            step *= 2;
            left = !left;
        }
        return head;
    }
}
int lastRemaining(int n) {
    int head = 1, step = 1; bool left = true;
    while (n > 1) {
        if (left || n % 2 == 1) head += step;
        n /= 2; step *= 2; left = !left;
    }
    return head;
}
Time: O(log n) Space: O(1)