Skip to content
Programmingoneonone
Programmingoneonone
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

Leetcode Elimination Game problem solution

YASH PAL, 31 July 202422 January 2026

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

Leetcode Elimination Game 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)

Elimination Game 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 solutions Leetcode Problems Solutions Leetcode

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes