AlgoMaster Logo

Time Needed to Buy Tickets

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Simulation with a Queue

Intuition:

  • The problem can be solved using a simulation approach. We process each person in the queue, decrementing their required tickets and tracking the number of rounds needed until the target person at the given index finishes purchasing tickets.
  • A direct simulation using a queue data structure is intuitive, representing each person's tickets as nodes in the queue.

Steps:

  1. Create a queue to simulate the people buying tickets one at a time.
  2. For each tick of time, decrement the ticket count required by the person currently at the front of the queue.
  3. If a person's ticket count is still more than zero, enque them at the end with their updated ticket count.
  4. Track the total time and stop when the target person has finished buying tickets.

Code:

2. Optimized Simulation without Queue

Intuition:

  • Instead of simulating the queue movement explicitly, we can calculate the time directly by keeping track of the number of decrements each person can afford until the k-th person is done.
  • We merely check how people in positions relative to k (i <= k or i > k) behave, as people cannot use more tickets than the i-th index allows before the k-th person is depleted.

Steps:

  1. Iterate through each person. For each person:
    • If they are before or at k, they need their tickets minus the greater of their need or the k-th person.
    • If they are after k, they need their tickets but can only use as much as the k-th person allows.
  2. Sum these time increments and return.

Code: