Leetcode 390. Elimination Game
You are given an integer n
. An elimination game involves an array of integers from 1 to n
. The game will be played based on the following rules:
For example, given n = 9
, the elimination steps are as follows:
The last remaining element is 6
.
n
be zero or negative?
n
is guaranteed to be a positive integer.n
.To solve this problem, we need to recognize a pattern or adopt a mathematical approach rather than simulating the entire process, which would be inefficient for large values of n
.
Let’s break down the approach:
The approach maintains the invariant that after each full sequence of eliminations, the problem reduces in size but stays consistent in structure.
Here is the C++ code to solve the problem:
class Solution {
public:
int lastRemaining(int n) {
int left = 1;
int step = 1;
bool fromLeft = true;
while (n > 1) {
// If we are eliminating from the left or the number of elements remaining is odd
if (fromLeft || n % 2 == 1) {
left += step;
}
// Double the step size and halve the number of elements remaining
step *= 2;
n /= 2;
// Switch direction
fromLeft = !fromLeft;
}
return left;
}
};
The time complexity of this solution is O(log n)
because in each step, the size of the problem is halved. This logarithmic complexity ensures that the solution is efficient even for very large values of n
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?