#2073

Time Needed to Buy Tickets

Easy
ArrayQueueSimulationSimulationQueue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of simulating every ticket purchase, we can calculate the time directly based on the number of tickets the kth person wants and the number of people in front of them. This approach is more efficient and avoids unnecessary iterations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the total time taken by the people in front of the kth person who still have tickets.
  2. 2Step 2: Add the tickets the kth person wants to the total time.
  3. 3Step 3: Return the total time.
solution.py6 lines
1def timeNeededToBuy(tickets, k):
2    time = 0
3    for i in range(len(tickets)):
4        if tickets[i] > 0:
5            time += min(tickets[i], tickets[k])
6    return time + tickets[k]

Complexity note: The time complexity is O(n) because we only need to iterate through the list of tickets once to calculate the total time.

  • 1The number of tickets a person has affects the total time taken.
  • 2People in front of the kth person can delay their ticket buying.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.