NeetCode #86LC-2073EasyArrays & Hashing
← Back to All Problems#86 · #2073 · Time Needed to Buy Tickets(买票需要的时间)
📌 Problem Statement & Constraints
There are
n people in a queue, tickets[i] is the number of tickets person i wants, and each ticket takes exactly 1 second to buy. A person leaves the queue after buying all their tickets. Return the time taken for the person at position k (0-indexed) to finish. Constraints: 1 <= n <= 100, 1 <= tickets[i] <= 100.💡 Core Algorithmic Approaches
- Only people at or before position
kcan buy more thantickets[k]tickets beforekfinishes. - People before
k(includingk) buy at mostmin(tickets[i], tickets[k])tickets in that window. - People after
kget at mosttickets[k] - 1turns, sincekleaves before they would need the last round. - Summing these bounds gives the answer directly in O(n), avoiding a full round-by-round simulation.
💻 Benchmark Python3 Implementation
class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
target = tickets[k]
total = 0
for i, t in enumerate(tickets):
if i <= k:
total += min(t, target) # gets at most tickets[k] turns
else:
total += min(t, target - 1) # k leaves before the final round
return total⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass with O(1) work per person.
💾 Space Complexity
O(1): two counters.
⚠️ Interview Pitfalls & Follow-ups
- Using
tickets[k]for everyone afterk: they get one fewer turn, becausekfinishes and leaves before their last round completes. - Simulating the queue round by round: O(sum(tickets)) which can be 10^4 here -- acceptable, but the direct formula is cleaner and generalises.
- Off-by-one on the
i <= kboundary: personkthemselves must use the fulltickets[k], so the condition is inclusive. - Multiplying
tickets[k] * n: ignores that some people want fewer tickets.