Elimination Game - Problem

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.

Input & Output

Example 1 — Small Case
$ Input: n = 9
Output: 6
💡 Note: arr = [1,2,3,4,5,6,7,8,9]. Round 1 (L→R): remove 1,3,5,7,9 → [2,4,6,8]. Round 2 (R→L): remove 8,4 → [2,6]. Round 3 (L→R): remove 2 → [6].
Example 2 — Even Number
$ Input: n = 10
Output: 8
💡 Note: arr = [1,2,3,4,5,6,7,8,9,10]. Round 1 (L→R): remove 1,3,5,7,9 → [2,4,6,8,10]. Round 2 (R→L): remove 10,6,2 → [4,8]. Round 3 (L→R): remove 4 → [8].
Example 3 — Minimum Case
$ Input: n = 1
Output: 1
💡 Note: Only one element [1], no elimination needed, return 1.

Constraints

  • 1 ≤ n ≤ 109

Visualization

Tap to expand
Elimination Game OverviewInput: n = 10, Array = [1,2,3,4,5,6,7,8,9,10]12345678910After Round 1 (L→R): [2,4,6,8,10]246810After Round 2 (R→L): [4,8]48Final Result: 88Optimal ApproachInstead of simulating:• Track first element position• Track step size (doubles each round)• Update based on direction & parityTime: O(log n) vs O(n log n)Space: O(1) vs O(n)Round 1: first=2, step=2Round 2: first=4, step=4Round 3: first=8, done!
Understanding the Visualization
1
Input Array
Start with [1,2,3,4,5,6,7,8,9,10]
2
Elimination Process
Alternately remove every other element from left and right
3
Mathematical Tracking
Track first element and step size: O(log n) solution
Key Takeaway
🎯 Key Insight: Track the position mathematically instead of simulating the entire elimination process
Asked in
Google 35 Microsoft 28 Amazon 22
28.5K Views
Medium Frequency
~25 min Avg. Time
842 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