Elimination Game - Problem
The Elimination Game Challenge

Imagine you're playing a strategic elimination game with a list of consecutive integers from 1 to n. The rules are simple but the pattern is fascinating:

🎯 Round 1: Start from the left, eliminate every other number (1st, 3rd, 5th, ...)
🎯 Round 2: From the remaining numbers, start from the right, eliminate every other number
🎯 Round 3: Back to left, eliminate every other number
🎯 Continue alternating directions until only one number survives!

For example, with n = 9:
• Start: [1,2,3,4,5,6,7,8,9]
• Left→: [2,4,6,8] (removed 1,3,5,7,9)
• ←Right: [2,6] (removed 4,8)
• Left→: [6] (removed 2)

Your mission: Given n, find the last survivor without actually simulating the entire elimination process!

Input & Output

example_1.py — Small Case
$ Input: n = 9
Output: 6
💡 Note: Starting with [1,2,3,4,5,6,7,8,9]. Round 1 (left→right): remove 1,3,5,7,9 → [2,4,6,8]. Round 2 (right←left): remove 8,4 → [2,6]. Round 3 (left→right): remove 2 → [6]. The last remaining number is 6.
example_2.py — Even Case
$ Input: n = 4
Output: 2
💡 Note: Starting with [1,2,3,4]. Round 1 (left→right): remove 1,3 → [2,4]. Round 2 (right←left): remove 4 → [2]. The last remaining number is 2.
example_3.py — Edge Case
$ Input: n = 1
Output: 1
💡 Note: With only one number [1], no elimination is needed. The last (and only) remaining number is 1.

Constraints

  • 1 ≤ n ≤ 109
  • Large input values require efficient O(log n) solution
  • Integer overflow is not a concern for this problem

Visualization

Tap to expand
Mathematical vs Simulation Approach❌ Simulation ApproachStores all remaining elementsTime: O(n²), Space: O(n)Slow for large inputs✅ Mathematical ApproachTracks only position + step sizeTime: O(log n), Space: O(1)Fast for any input sizeKey Mathematical InsightPosition Update Formulaif (leftToRight || remaining % 2 == 1) {start += step;}step *= 2;remaining /= 2;leftToRight = !leftToRight;O(log n)O(1) spaceWorks for n=10⁹No simulation
Understanding the Visualization
1
Pattern Recognition
Each round eliminates exactly half the remaining elements
2
Position Tracking
We only need to track the first remaining position and spacing
3
Update Rules
Start position changes based on direction and parity
4
Convergence
Continue until only one position remains
Key Takeaway
🎯 Key Insight: Instead of simulating the entire elimination process, track only the mathematical position and spacing pattern, reducing complexity from O(n²) to O(log n)!
Asked in
Google 25 Microsoft 18 Amazon 15 Apple 12
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen