Last Remaining Integer After Alternating Deletion Operations Problem
Description
LeetCode Problem 3782.
You are given an integer n.
We write the integers from 1 to n in a sequence from left to right. Then, alternately apply the following two operations until only one integer remains, starting with operation 1:
- Operation 1: Starting from the left, delete every second number.
- Operation 2: Starting from the right, delete every second number.
Return the last remaining integer.
Example 1:
Input: n = 8
Output: 3
Explanation:
- Write [1, 2, 3, 4, 5, 6, 7, 8] in a sequence.
- Starting from the left, we delete every second number: [1, 2, 3, 4, 5, 6, 7, 8]. The remaining integers are [1, 3, 5, 7].
- Starting from the right, we delete every second number: [1, 3, 5, 7]. The remaining integers are [3, 7].
- Starting from the left, we delete every second number: [3, 7]. The remaining integer is [3].
Example 2:
Input: n = 5
Output: 1
Explanation:
- Write [1, 2, 3, 4, 5] in a sequence.
- Starting from the left, we delete every second number: [1, 2, 3, 4, 5]. The remaining integers are [1, 3, 5].
- Starting from the right, we delete every second number: [1, 3, 5]. The remaining integers are [1, 5].
- Starting from the left, we delete every second number: [1, 5]. The remaining integer is [1].
Example 3:
Input: n = 1
Output: 1
Explanation:
- Write [1] in a sequence.
- The last remaining integer is 1.
Constraints:
1 <= n <= 10^15
Solution
Approach: Track an Arithmetic Progression
With n up to 1015 we cannot simulate the deletions, but the survivors always form an arithmetic progression, so three numbers describe them: the first value first, the gap step between neighbours, and how many remain, count. Initially first = 1, step = 1, count = n.
Each round halves the list and doubles the gap:
- Deleting from the left removes the 2nd, 4th, ... numbers. The first number survives, and
countbecomesceil(count / 2). - Deleting from the right removes the 2nd, 4th, ... numbers counted from the right. If
countis odd, the first number survives. Ifcountis even, the first number is deleted and the new first isfirst + step. Againcountbecomesceil(count / 2).
In both cases step doubles. Alternate the two kinds of round until count == 1; then first is the answer. The loop runs about log2 n times.
Complexity: O(log n) time and O(1) extra space.
class Solution:
def lastInteger(self, n: int) -> int:
first, step, count, from_left = 1, 1, n, True
while count > 1:
# deleting from the right with an even count removes the first number
if not from_left and count % 2 == 0:
first += step
step *= 2
count = (count + 1) // 2
from_left = not from_left
return first