Skip to main content
Back to problems
Leetcode
Medium
Arrays
Queues
Simulation
Amazon
Time Needed To Buy Tickets

Compute how long it takes for a specific person to finish buying tickets when people are served in round-robin order.

Acceptance 100%
Problem Statement

Problem

There is a line of people waiting to buy tickets. The ii-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 where tickets[i] is the number of tickets person i wants.
  • 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

  • 1tickets.length1001 \le tickets.length \le 100
  • 1tickets[i]1001 \le tickets[i] \le 100
  • 0k<tickets.length0 \le k < tickets.length

These bounds are consistent with the standard interview/online-judge formulation of this problem.

Examples
Sample cases returned by the problem API.

Example 1

Input

tickets = [2,3,2], k = 2

Output

6

Explanation

A possible sequence of purchases is:

  1. person 0 buys 1 ticket
  2. person 1 buys 1 ticket
  3. person 2 buys 1 ticket
  4. person 0 buys 1 ticket and leaves
  5. person 1 buys 1 ticket
  6. 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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.