1556. Halving Circle Survivor
A festival string of n paper lanterns hangs in a closed loop, numbered 1 to n in order. A caretaker starts at lantern 1, leaves it burning, snuffs out lantern 2, leaves lantern 3 burning, snuffs out lantern 4, and keeps walking around the loop in the same direction, always alternating between "leave lit" and "snuff out" and stepping over lanterns that are already dark. The alternation never resets when the walk passes lantern n; it simply continues with the next burning lantern.
The walk ends when exactly one lantern is still lit. Given n, return the number of that last lantern. Since n can be enormous, simulating is not allowed: use O(log n) time (or better) and O(1) space.
Example 1
- Input:
- n = 7
- Output:
- 7
- Explanation:
Lanterns 2, 4, 6, 1, 5 and 3 go dark in that order, leaving lantern 7 as the last one lit.
Example 2
- Input:
- n = 10
- Output:
- 5
- Explanation:
The even lanterns go dark first, then 3, 7, 1 and 9, leaving lantern 5.
Constraints
1 ≤ n ≤ 1015
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(log n)
- Space
- O(1)