Social feed~25 min2s · 256 MBtarget O(n × min(k, n)) time, O(n) spaceclassic twin: lc-1823queues
A social app runs a live giveaway. The entrants stand in a circle, numbered 1 to n in order, and the host starts counting at entrant 1.
The host counts k entrants, starting with the one at the start. The entrant at the count of k is out, and counting restarts from the next entrant. Rounds go on until one entrant remains, and that entrant wins.
Write last_entrant(n, k).
n, in a circle. Counting starts at entrant 1.k entrants, including the one where the count starts, going round the circle. The entrant at the count of k is removed, and the next round starts from the entrant after them.Input: n = 6, k = 3
Output: 1A queue holds the circle, front first. To count k, move the first k - 1 entrants from the front to the back. The entrant now at the front is out.
| Round | Circle before (front first) | Moved to the back | Out |
|---|---|---|---|
| 1 | 1, 2, 3, 4, 5, 6 | 1, 2 | 3 |
| 2 | 4, 5, 6, 1, 2 | 4, 5 | 6 |
| 3 | 1, 2, 4, 5 | 1, 2 | 4 |
| 4 | 5, 1, 2 | 5, 1 | 2 |
| 5 | 5, 1 | 5, 1 | 5 |
Entrant 1 is left, so the answer is 1.
Input: n = 5, k = 1
Output: 5With k = 1 the entrant at the start is out each round, so they go in order and the last entrant wins.
Input: n = 4, k = 6
Output: 3A count of 6 in a circle of 4 goes round the circle once and a half. Moving whole laps changes nothing, so only 5 mod 4 = 1 move matters in the first round.
1 ≤ n ≤ 50001 ≤ k ≤ 5000Each round moves up to k - 1 entrants, and there are n - 1 rounds. For n = 5000 and k = 5000, counting off one entrant at a time is about 25 million moves.
A move is a constant-time queue step. Moving (k - 1) modulo the circle size is enough, because whole laps return every entrant to where they were. That cuts the moves to about 4.4 million for n = k = 5000.