Problem 1701

Abstract / Summary

Calculate the average waiting time for people in a queue where each person waits for all ahead of them before being served.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
9 lines | 294 bytes | submitted November 3, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 duration yields the new finish time after serving the current customer.
  • Subtracting arrive from the updated done gives the waiting time for the current customer, which is then accumulated in wait.

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.11 | σ = 1.20

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
27 links | 14 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

13 solutions   November 3, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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