Compute how long it takes for a specific person to finish buying tickets when people are served in round-robin order.
Problem
There is a line of people waiting to buy tickets. The -th person needs to buy tickets[i] tickets. Each second, the person at the front of the line buys exactly one ticket, and then:
- if they still need more tickets, they go to the back of the line;
- otherwise, they leave the line.
You are given an array tickets and an index k. Return the total number of seconds required for the person initially at index k to finish buying all of their tickets.
Intuition
The line behaves like a repeated cycle over the current order. You only need to count how many times each person gets served before person k is done, while respecting that people after k do not get one final turn once k finishes.
Input Format
tickets: an array of positive integers wheretickets[i]is the number of tickets personiwants.k: the index of the target person in the original line.
Output Format
Return a single integer: the number of seconds until person k has bought all required tickets.
Constraints
These bounds are consistent with the standard interview/online-judge formulation of this problem.
Example 1
Input
tickets = [2,3,2], k = 2
Output
6
Explanation
A possible sequence of purchases is:
- person 0 buys 1 ticket
- person 1 buys 1 ticket
- person 2 buys 1 ticket
- person 0 buys 1 ticket and leaves
- person 1 buys 1 ticket
- person 2 buys 1 ticket and leaves
Person 2 finishes after 6 seconds.
Example 2
Input
tickets = [5,1,1,1], k = 0
Output
8
Explanation
Person 0 needs 5 turns. Everyone else can only take one turn before leaving. The total time is 5 + 1 + 1 + 1 = 8 seconds.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.