Time Needed to Buy Tickets - Problem

There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.

You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].

Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.

Return the time taken for the person initially at position k (0-indexed) to finish buying tickets.

Input & Output

Example 1 — Basic Case
$ Input: tickets = [2,3,2], k = 2
Output: 6
💡 Note: Person 2 needs 2 tickets. In the queue: P0 buys 2 tickets (takes 2 seconds), P1 buys 2 tickets before P2 finishes (takes 2 seconds), P2 buys 2 tickets (takes 2 seconds). Total: 6 seconds.
Example 2 — First Person
$ Input: tickets = [5,1,1,1], k = 0
Output: 8
💡 Note: Person 0 needs 5 tickets. Others buy 1 ticket each while P0 gets their 5 tickets. Total: 5 + 1 + 1 + 1 = 8 seconds.
Example 3 — Single Person
$ Input: tickets = [1], k = 0
Output: 1
💡 Note: Only one person needs 1 ticket, takes 1 second.

Constraints

  • 1 ≤ n ≤ 100
  • 1 ≤ tickets[i] ≤ 100
  • 0 ≤ k < n

Visualization

Tap to expand
Time Needed to Buy Tickets INPUT Queue of People P0 P1 P2 k=2 tickets[] array: 2 [0] 3 [1] 2 [2] Input Values: tickets = [2, 3, 2] k = 2 (target person) ALGORITHM STEPS 1 Calculate for i < k min(tickets[i], tickets[k]) P0: min(2,2)=2, P1: min(3,2)=2 2 Add tickets[k] Person k buys all tickets P2: tickets[2] = 2 3 Calculate for i > k min(tickets[i], tickets[k]-1) No one after k in this case 4 Sum All Times Total = 2 + 2 + 2 = 6 Calculation: P0: min(2,2) = 2 sec P1: min(3,2) = 2 sec P2: 2 sec (target) FINAL RESULT Timeline Simulation P0 t=1 P1 t=2 P2 t=3 P0 t=4 P1 t=5 P2 t=6 Output: 6 Time = 6 seconds OK Person at k=2 finishes buying tickets at t=6 (after 2 rounds) Key Insight: Mathematical approach avoids simulation: For people BEFORE k (indices 0 to k-1), they can buy at most min(tickets[i], tickets[k]) tickets. For people AFTER k, they can buy at most min(tickets[i], tickets[k]-1) tickets because they get one less turn. This gives O(n) time complexity instead of simulating the queue. TutorialsPoint - Time Needed to Buy Tickets | Mathematical Calculation Approach
Asked in
Amazon 15 Microsoft 8
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen