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: tickets=[2,3,2], k=2Input:232P0P1P2 (k=2)Process:Each person buys 1 ticket per secondAfter buying, goes to back of lineContinue until person k finishesTimeline:P0P1P2P0P1P2Seconds: 1 2 3 4 5 6Output: 6 seconds (when person k=2 finishes)
Understanding the Visualization
1
Input
Array of ticket needs and target person k
2
Process
People buy tickets one at a time, cycling through queue
3
Output
Time when person k finishes buying all tickets
Key Takeaway
🎯 Key Insight: Calculate contributions mathematically instead of simulating the entire queue process
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