Skip to content
Problem 390 · LeetCode 390(opens in a new tab)

Elimination Game

MediumMath

Write the numbers 1 to n in a row, in increasing order. Now remove numbers in passes. The first pass goes left to right: it removes the leftmost number, keeps the next, removes the one after, and so on, alternating to the end of the row.

The second pass does the same from right to left on what is left: it removes the rightmost number, keeps the next one, and so on. Passes keep switching direction until a single number is left. Return that number.

Example 1

Input:  n = 10
Output: 8
Why:    10 numbers → 2 4 6 8 10 → 4 8 → 8
2 more examples and the constraints

Example 2

Input:  n = 6
Output: 4
Why:    6 numbers → 2 4 6 → 4

Example 3

Input:  n = 1
Output: 1
Why:    one number is already the last one left

Constraints

  • 1 ≤ n ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recurse on the half that is leftO(log n)
  2. Track only the headO(log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 1,000,000,000Verdict
Recurse on the half that is leftO(log n)
Passes; neat mirror trick
Track only the headO(log n)
Best; no stack at all

n = how many numbers start in the row. Both do about 30 rounds at the limit; simulating the list would need about 2,000,000,000 moves.

Edge cases to test

  • n = 1. No pass runs; the answer is 1.
  • n = 2. The first pass removes 1, so 2 is left.
  • Odd count on a right pass. With 5 left, the pass from the right also removes the head. With 4 left, it does not.
  • n at the limit. 1,000,000,000 needs only about 30 passes, and the answer never exceeds n, so a 32-bit int is enough.

Common mistakes

  • Building the list for large n: it runs out of time and memory.
  • Moving the head on every right-to-left pass, not only when the count is odd.
  • Forgetting to double step after each pass, so the head moves by the wrong amount.

How to talk through it

  1. 1Clarify. How large can n be? Is it the numbers 1 to n with no gaps?
  2. 2Name the simulation. Delete every other number per pass; say it needs O(n) time and memory, too much for a billion.
  3. 3Spot the shape. What is left is always evenly spaced: a head, a gap and a count describe it.
  4. 4Code the head walk. Move the head on left passes and on right passes with an odd count; halve the count, double the gap.
  5. 5Test out loud. Run n = 1, n = 2 and n = 10 by hand.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?