Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Elimination Game problem solution

YASH PAL, 31 July 2024

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);
}

coding problems

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes