Elimination Game

Medium Recursion

The whole numbers from 1 to n stand in a row, smallest first.

Rounds of crossing out follow, until only one number is left. The first round goes from left to right: it crosses out the first number still standing, skips the next, crosses out the one after, and so on to the end of the row. The second round does the same from right to left, starting with the last number still standing. The rounds go on like that, turning round each time.

Return the number that is left at the end.

Example 1

Input: n = 10
Output: 8

From the left, 1, 3, 5, 7 and 9 go, leaving 2, 4, 6, 8 and 10. From the right, 10, 6 and 2 go, leaving 4 and 8. From the left again, 4 goes, and 8 is left.

Example 2

Input: n = 24
Output: 14

Example 3

Input: n = 2
Output: 2

Constraints

  • 1 ≤ n ≤ 10⁹

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

More Recursion

All Recursion problems