Time Needed to Buy Tickets

Task example: Time Needed to Buy Tickets

Each person buys one ticket per second. If they need more, they join the back; otherwise they leave. Return the seconds until the person originally at index k finishes. Keep their original identity even as the line moves.

Example 1
Input
tickets = [3, 2, 4]
k = 1
Output
5

People 0, 1, 2, 0, 1 buy tickets. Person 1 finishes at second 5, so stop before person 2 buys again.

Example 2
Input
tickets = [5, 1, 1, 1]
k = 0
Output
8

After everyone else leaves, person 0 continues alone and finishes at second 8.

The task allows 1 to 100 people, each needing 1 to 100 tickets. The interactive demo uses smaller limits to keep the trace readable.

LeetCode 2073 ↗
01 / Queue simulation

Queue simulation: video explanation

tickets = [3, 2, 4]
k = 1
→ 5

Prefer reading? Follow the steps below.

  1. Copy the ticket counts and put the original person indices into a deque. Start the elapsed time at zero.
  2. Remove the front index, subtract one ticket, and add one second. If this is k and no tickets remain, return immediately.
  3. If the person still needs tickets, append their index to the back. Otherwise they leave. Repeat until k finishes.

Time complexity · O(n + T)

Here n is the number of people and T is the purchases made before k finishes. Setup takes O(n); each deque purchase takes O(1).

Space complexity · O(n)

The copied counts and queue both use space proportional to the number of people.

PYTHONLive code trace
02 / Count contributions (optimal)

Count contributions: video explanation

tickets = [3, 2, 4]
k = 1
→ 5

Prefer reading? Follow the steps below.

  1. Let target = tickets[k]. At or before k, each person buys min(count, target) tickets before we stop.
  2. After k, each person buys min(count, target - 1). Their turn in the final round never happens.
  3. Add these contributions and return the total. Taking the minimum also handles people who finish early.

Counting avoids repeated purchases: one pass gives the same answer, even when ticket counts are large.

Time complexity · O(n)

Visit each person once, regardless of how many tickets they need.

Space complexity · O(1)

Only a few counters are used. Neither approach changes the original input.

PYTHONLive code trace

Time Needed to Buy Tickets

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.