All problems
0654MediumMathRecursion

Last Ticket on the Table

Tracked in this browser only
Write code

Trains the technique from

LeetCode 390Elimination Game

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Raffle tickets numbered 1 through n are laid out on a table in a single row, in increasing order. A steward then thins the row out in sweeps.

The first sweep runs from the left end to the right end: the steward takes the first ticket still on the table, leaves the next one, takes the one after that, and so on to the far end. The second sweep runs from the right end back to the left, following the same take-one-leave-one rhythm starting with the ticket at the right end. Sweeps keep alternating direction like this until a single ticket is left.

Return the number printed on that last ticket.

Examples

Example 1

Input
n = 6
Output
4

The first sweep takes 1, 3 and 5, leaving 2, 4, 6. The second sweep starts at the right end, taking 6 and then 2, so ticket 4 is the one left.

Example 2

Input
n = 24
Output
14

The four sweeps leave 2, 4, 6, ..., 24; then 2, 6, 10, 14, 18, 22; then 6, 14, 22; and finally ticket 14 on its own.

Example 3

Input
n = 8
Output
6

The first sweep leaves 2, 4, 6, 8. The second runs from the right, taking 8 and then 4, which leaves 2 and 6. The third runs from the left and takes 2, so ticket 6 is the survivor.

Constraints

  • 1 <= n <= 10^9

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def last_ticket(n: int) -> int:
Java
public int lastTicket(int n)
September 7
Apply