Magicsheet logo

Time Needed to Buy Tickets

Easy
100%
Updated 6/1/2025

Time Needed to Buy Tickets

What is this problem about?

Imagine a queue of people waiting to buy tickets. Each person i wants to buy a specific number of tickets tickets[i]. It takes 1 second to buy a single ticket. After buying a ticket, if a person still needs more, they move to the back of the queue. Given the ticket requirements of everyone in the queue and the position k of a specific person, how many seconds will it take for that person to finish buying all their tickets?

Why is this asked in interviews?

This time needed to buy tickets interview question is an "easy" level problem used by companies like Uber, Microsoft, and Meta. It tests your ability to simulate a queue-based process and potentially identify a mathematical shortcut to avoid a full simulation. It evaluates your understanding of basic data structures (queues) and your ability to optimize simple loops.

Algorithmic pattern used

This problem follows the Array, Queue, Simulation interview pattern.

  1. Simulation approach: Use a queue to store (index, tickets_needed). Rotate through the queue, decrementing the tickets and incrementing a time counter until person k reaches 0 tickets.
  2. Mathematical approach (O(N)):
    • For any person i before or at position k, they will buy at most tickets[k] tickets (or fewer if they need less).
    • For any person i after position k, they will buy at most tickets[k] - 1 tickets because person k finishes their last ticket before those people get their next turn.
    • Total time = sum(min(tickets[i], limit)) for all i.

Example explanation

Tickets: [2, 3, 2], k = 2 (The person who wants 2 tickets at the end).

  1. Person 0 buys 1 ticket, moves to back. Time=1, Tickets=[3, 2, 1].
  2. Person 1 buys 1 ticket, moves to back. Time=2, Tickets=[2, 1, 2].
  3. Person 2 buys 1 ticket, moves to back. Time=3, Tickets=[1, 2, 1].
  4. Person 0 buys 1 ticket, finished. Time=4, Tickets=[2, 1].
  5. Person 1 buys 1 ticket, moves to back. Time=5, Tickets=[1, 1].
  6. Person 2 buys 1 ticket, finished. Time=6. Result: 6.

Common mistakes candidates make

In "Time Needed to Buy Tickets coding problem," a common mistake is an "off-by-one" error in the mathematical shortcut, such as counting too many tickets for people behind position k. Another error is using a full simulation when the input sizes are large, which could lead to slow performance compared to the O(n) sum approach.

Interview preparation tip

When you see a simulation problem where you only care about one specific element, try to calculate its contribution and the contribution of its neighbors directly. This "contribution-based" thinking is a key step toward optimizing many simulation and array problems.

Similar Questions