Python 1701.py
class Solution:
def averageWaitingTime(self, customers: List[List[int]]) -> float:
done = 0
wait = 0
for arrive, duration in customers:
done = max(done, arrive) + duration
wait += done - arrive
return wait / len(customers)
Difficulty
and has an acceptance rate of about 73% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the average waiting time for a sequence of customers served by a single server. Each customer is described by an arrival time and a service duration. The algorithm processes the customers in the given order, maintains the time at which the server becomes free, accumulates the total waiting time, and finally returns the average.
Key Steps
Initialization
The algorithm begins by setting two accumulator variables to zero. One variable tracks the moment the server finishes serving the last processed customer, while the other aggregates the total waiting time experienced by all customers.
done = 0
wait = 0
Iteration Over Customers
A single loop iterates through each pair of arrival time and service duration. The loop body updates the server’s finish time and adds the individual waiting time to the total.
for arrive, duration in customers:
done = max(done, arrive) + duration
wait += done - arrive
- The expression
max(done, arrive)ensures that the server starts serving the current customer either when it becomes free (done) or when the customer arrives (arrive), whichever is later. - Adding
durationyields the new finish time after serving the current customer. - Subtracting
arrivefrom the updateddonegives the waiting time for the current customer, which is then accumulated inwait.
Final Computation
After processing all customers, the algorithm divides the accumulated waiting time by the number of customers to obtain the average.
return wait / len(customers)
Edge Cases Handled
The logic gracefully accommodates scenarios where a customer arrives after the server has been idle. In such cases, max(done, arrive) selects the later arrival time, causing the server to wait idle until the new customer appears. Conversely, when customers arrive while the server is still busy, the same expression selects the current done value, causing the new customer to wait for the ongoing service to finish. The algorithm also works correctly for a single-customer input, where the waiting time reduces to the service duration itself. When multiple customers share the same arrival time, the server processes them sequentially, and each subsequent customer’s waiting time includes the durations of the earlier customers in that batch.
Performance Optimizations
The implementation achieves optimal performance by using a single pass over the input list, avoiding any auxiliary data structures. All calculations are performed with primitive arithmetic operations, which keep the runtime overhead minimal. By updating the done variable in place, the code eliminates the need for temporary storage of intermediate states. The use of max directly within the loop eliminates a conditional branch, allowing the interpreter to evaluate the necessary start time in a concise expression. This streamlined approach ensures that the algorithm scales linearly with the number of customers while maintaining a low constant factor.
ELI5 - Simplified Explanation
Imagine a busy little pizza shop where hungry friends come one after another. Every friend tells the chef when they get to the shop and how long they want their pizza to take to cook.
The computer keeps track of two things. First, it watches the clock to know when the pizza oven will finally be free to start a new job. Second, it keeps a tally of all the minutes friends spend waiting.
When a new friend arrives, the chef checks the time. If the oven is still cooking a previous pizza, the new friend has to wait for the oven to finish. If the oven is empty, the chef starts right away. The new friend waits from the moment they walk through the door until their pizza is hot and ready.
Once the pizza is finished, the computer adds those minutes to the big tally. After everyone has been served, the computer looks at all those waiting minutes and shares them out so it can tell you the average time one person spent waiting.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | JS | Java | Python | Go | Rust | TS | ||
| MemoryLimitExceeded | C++ | TS | |||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| MemoryLimitExceeded | TypeScript, C++ | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 1317: Convert Integer to the Sum of Two No-Zero Integers
- problem 1417: Reformat The String
- problem 1556: Thousand Separator
- problem 1790: Check if One String Swap Can Make Strings Equal
- problem 2259: Remove Digit From Number to Maximize Result
- problem 2582: Pass the Pillow
- problem 2605: Form Smallest Number From Two Digit Arrays
- problem 2729: Check if The Number is Fascinating
- problem 881: Boats to Save People
- problem 1503: Last Moment Before All Ants Fall Out of a Plank
- problem 1578: Minimum Time to Make Rope Colorful
- problem 1685: Sum of Absolute Differences in a Sorted Array
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality