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 - Mathematical Pattern INPUT Initial Array [1, n] n = 9 1 2 3 4 5 6 7 8 9 Round 1: Left to Right 1 2 3 4 5 6 7 8 9 Remaining: 2,4,6,8 Round 2: Right to Left 2 4 6 8 Remaining: 2,6 Round 3: Left to Right 2 6 Remaining: 6 Input: n = 9 ALGORITHM STEPS 1 Initialize Variables head=1, step=1, remaining=n left=true (direction flag) 2 Update Head Position If going left OR remaining is odd: head += step 3 Halve Count remaining = remaining / 2 step = step * 2 left = !left (toggle) 4 Repeat Until Done While remaining > 1 repeat steps 2-3 Return head value Trace: head=1,2,2,6 step=1,2,4,8 | rem=9,4,2,1 FINAL RESULT After all eliminations: 6 The last remaining number is 6 Elimination Summary: [1..9] --> [2,4,6,8] [2,4,6,8] --> [2,6] --> [6] Output: 6 Key Insight: Instead of simulating the elimination, use mathematical pattern: track the head position. Head updates when going left-to-right OR when remaining count is odd (rightmost gets removed). Time: O(log n) | Space: O(1) - Much faster than O(n) simulation approach! TutorialsPoint - Elimination Game | Mathematical Pattern Approach
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