QueueEasy

Time to Buy Tickets Visualizer

What is Time to Buy Tickets

People stand in a queue to buy tickets. tickets[i] is how many tickets person i still needs. Each second, the person at the front buys one ticket and goes to the rear if they still need more. Return the second when person k finishes.

Approach

You can simulate the queue. A faster count is: everyone at or before k buys min(their tickets, tickets[k]), and everyone after k buys min(their tickets, tickets[k] - 1).

Visualization & algorithm

The queue, front and rear marked
while person k still needs a ticket:
front buys one
time += 1
if front still needs more: move to the rear
return time
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
Fast countO(n)Each person contributes one min().
SimulationO(sum of tickets)Fine for a short picture, slow if every person wants many tickets.

Implementation

def solve(self, tickets, k):
    need = tickets[k]
    time = 0
    for i, x in enumerate(tickets):
        if i <= k: time += min(x, need)
        else: time += min(x, need - 1)
    return time