LeetCode 390: Elimination Game Solution

Master LeetCode problem 390 (Elimination Game), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

390. Elimination Game

Problem Explanation

Explanation

The problem can be solved by simulating the elimination process. We can keep track of the leftmost element, the current step size, and the direction of traversal. At each step, we update the leftmost element and the step size according to the rules of the elimination process until only one element remains.

Algorithmic Idea

  1. Initialize left to 1, step to 1, remaining to n, and isLeftToRight to true.
  2. While remaining > 1:
    • If isLeftToRight is true or remaining is odd, update left to left + step.
    • Update remaining to remaining / 2.
    • Double the step.
    • Toggle the value of isLeftToRight.
  3. Return left.

Time Complexity

The time complexity of this algorithm is O(log n) as we reduce the size of the problem by half at each step.

Space Complexity

The space complexity is O(1) as we only use a constant amount of extra space.

Solution Code

class Solution {
    public int lastRemaining(int n) {
        int left = 1, step = 1, remaining = n;
        boolean isLeftToRight = true;
        
        while (remaining > 1) {
            if (isLeftToRight || remaining % 2 == 1) {
                left += step;
            }
            remaining /= 2;
            step *= 2;
            isLeftToRight = !isLeftToRight;
        }
        
        return left;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 390 (Elimination Game)?

This page provides optimized solutions for LeetCode problem 390 (Elimination Game) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 390 (Elimination Game)?

The time complexity for LeetCode 390 (Elimination Game) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 390 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 390 in Java, C++, or Python.

Back to LeetCode Solutions