Time Needed to Buy Tickets — LeetCode 2073 Python Solution
- Problem
- #2073
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The 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].
Python solution
class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
ans = 0
for i, x in enumerate(tickets):
ans += min(x, tickets[k] if i <= k else tickets[k] - 1)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the queue |
| Space | O(1) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2073. Time Needed to Buy Tickets is filed here because LeetCode tags it Queue, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2073. Time Needed to Buy Tickets?
- LeetCode 2073. Time Needed to Buy Tickets is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2073. Time Needed to Buy Tickets?
- The Python solution on this page runs in O(n), where n is the length of the queue.
- What is the space complexity of LeetCode 2073. Time Needed to Buy Tickets?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2073. Time Needed to Buy Tickets cover?
- LeetCode 2073. Time Needed to Buy Tickets is tagged Queue, Array and Simulation on LeetCode.