Elimination Game Problem
Description
LeetCode Problem 390.
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.
Given the integer n, return the last number that remains in arr.
Example 1:
Input: n = 9
Output: 6
Explanation:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr = [2, 4, 6, 8]
arr = [2, 6]
arr = [6]
Example 2:
Input: n = 1
Output: 1
Constraints:
- 1 <= n <= 10^9
Solution
Approach: Track the Head of the List
Simulating the passes on a real list takes O(n) time and memory, which is too much for n up to 109. But after every pass the remaining numbers are still evenly spaced, so the list is fully described by three values:
head: the smallest number left,step: the gap between neighbouring numbers,remaining: how many numbers are left.
Each pass removes every other number, so remaining is halved (rounded down) and step doubles. The only question is whether the head is removed:
- A left-to-right pass always removes the first number, so the new head is
head + step. - A right-to-left pass starts from the last number. If
remainingis odd, it alternates back onto the first number and removes it too, so the head moves bystep. Ifremainingis even, the first number survives.
Repeat until one number is left; that number is head.
n = 9 head 1, step 1: 1 2 3 4 5 6 7 8 9
L -> R head 2, step 2: 2 4 6 8
R -> L head 2, step 4: 2 6 (4 numbers, even: 2 stays)
L -> R head 6, step 8: 6
Complexity: O(log n) time, since remaining halves on every pass, and O(1) space.
class Solution:
def lastRemaining(self, n: int) -> int:
head = 1 # smallest number still in the list
step = 1 # gap between neighbouring numbers still in the list
remaining = n # how many numbers are left
left_to_right = True
while remaining > 1:
# The head is removed on every left-to-right pass,
# and on a right-to-left pass only when the count is odd.
if left_to_right or remaining % 2 == 1:
head += step
remaining //= 2
step *= 2
left_to_right = not left_to_right
return head
Now write it from memory
Close the write-up and solve it yourself against the tests.