Average Waiting Time solution and explanation
9 more videos on this problem
Average Waiting Time - Leetcode 1701 - PythonNeetCodeIO · 9:15 · 8K views
Average Waiting Time | Simple Simulation | Leetcode 1701 | codestorywithMIKcodestorywithMIK · 17:03 · 6K views
Leetcode 1701. Average Waiting Time [Java]if else statement · 5:13 · 1K views
1701. Average Waiting Time (Leetcode Medium)Programming Live with Larry · 5:47 · 1K views
Leetcode 1701. Average Waiting TimeFraz · 5:27 · 545 views
AVERAGE WAITING TIME | LEETCODE 1701 | PYTHON SOLUTIONCracking FAANG · 7:57 · 393 views
Daily Leetcode #1561: Jul 09, 2024 - 1701. Average Waiting TimeProgramming Live with Larry · 5:15 · 377 views
LeetCode 1701. [Medium] Average Waiting TimeFrancesco Manicardi · 3:57 · 271 views
Leetcode 1701: Average Waiting TimeAlgorithms Casts · 9:30 · 240 views
Average Waiting Time (LeetCode 1701) (Array)CodeWithARB · 15:43 · 239 views
The problem
There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]:
arrivaliis the arrival time of theithcustomer. The arrival times are sorted in non-decreasing order.timeiis the time needed to prepare the order of theithcustomer.
When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input.
Return the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted.
Example 1:
Input: customers = [[1,2],[2,5],[4,3]] Output: 5.00000 Explanation: 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5.
Example 2:
Input: customers = [[5,2],[5,4],[10,3],[20,1]] Output: 3.25000 Explanation: 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.
Constraints:
1 <= customers.length <= 1051 <= arrivali, timei <= 104arrivali <= arrivali+1
Approach overview
Problem Overview: Each customer arrives at a specific time and needs a fixed amount of cooking time. The chef can handle only one order at a time. You process customers in arrival order and compute how long each customer waits from arrival until their food is finished. The goal is to return the average waiting time across all customers.
Approach 1: Straightforward Simulation (O(n) time, O(1) space)
This problem naturally maps to a simple simulation of the restaurant timeline. Maintain a variable currentTime representing when the chef becomes free. Iterate through the array of customers in order. For each customer, the chef starts cooking at max(currentTime, arrivalTime) because the chef may be idle if the next customer arrives later. The order finishes at startTime + cookTime, and the waiting time for that customer is finishTime - arrivalTime. Accumulate the waiting times and update currentTime to the finish time before moving to the next customer.
This works because the problem guarantees customers are already processed in arrival order. No sorting or complex data structures are required. The algorithm performs one pass through the list, making it O(n) time with constant extra space. This is essentially a direct simulation of the chef's workflow.
Approach 2: Event Simulation with Priority Queue (O(n log n) time, O(n) space)
A more general way to model the system is event-driven simulation. Instead of assuming sequential processing, treat each arrival and cooking completion as events. Store pending customers in a priority queue ordered by arrival time or availability. When the chef becomes free, pop the next customer and schedule the cooking completion event. Each event updates the global clock and contributes to the waiting time calculation.
This design is useful when extending the system to multiple chefs or more complex scheduling policies. The priority queue keeps the next event accessible in O(log n) time. While this approach is more flexible, it introduces unnecessary overhead for the single-chef constraint in this problem.
Recommended for interviews: The straightforward simulation is the expected solution. It shows that you can translate a real-world process into code and reason about time progression with a simple invariant: the chef starts the next order when both the chef and the customer are available. Mentioning the event-driven model can demonstrate deeper systems thinking, but the O(n) simulation is the cleanest and most efficient approach.
Approach 1: Approach 1: Straightforward Simulation
This approach involves simulating the process: for each customer, determine when their order can start based on the current time (when the previous order finishes) and calculate their waiting time.
You'll need to track the current time and update it as each order is processed.
def average_waiting_time(customers):
current_time = 0
total_waiting_time = 0.0
for arrival, time in customers:
current_time = max(current_time, arrival) + time
total_waiting_time += current_time - arrival
return total_waiting_time / len(customers)
customers = [[1, 2], [2, 5], [4, 3]]
print(f"{average_waiting_time(customers):.5f}")import java.util.List;
public class AverageWaitingTime {
public static double averageWaitingTime(List<int[]> customers) {
int currentTime = 0;
double totalWaitingTime = 0.0;
for(int[] customer : customers) {
int arrival = customer[0];
int time = customer[1];
currentTime = Math.max(currentTime, arrival) + time;
totalWaitingTime += currentTime - arrival;
}
return totalWaitingTime / customers.size();
}
public static void main(String[] args) {
List<int[]> customers = List.of(new int[]{1, 2}, new int[]{2, 5}, new int[]{4, 3});
System.out.printf("%.5f\n", averageWaitingTime(customers));
}
}#include <iostream>
#include <vector>
float averageWaitingTime(std::vector<std::pair<int,int>>& customers) {
int currentTime = 0;
float totalWaitingTime = 0.0;
for(auto& customer : customers) {
int arrival = customer.first;
int time = customer.second;
currentTime = std::max(currentTime, arrival) + time;
totalWaitingTime += currentTime - arrival;
}
return totalWaitingTime / customers.size();
}
int main() {
std::vector<std::pair<int, int>> customers = {{1,2},{2,5},{4,3}};
std::cout << std::fixed << std::setprecision(5) << averageWaitingTime(customers) << std::endl;
return 0;
}function averageWaitingTime(customers) {
let currentTime = 0;
let totalWaitingTime = 0;
for (const [arrival, time] of customers) {
currentTime = Math.max(currentTime, arrival) + time;
totalWaitingTime += currentTime - arrival;
}
return totalWaitingTime / customers.length;
}
const customers = [[1, 2], [2, 5], [4, 3]];
console.log(averageWaitingTime(customers).toFixed(5));#include <stdio.h>
float averageWaitingTime(int customers[][2], int size) {
int currentTime = 0;
float totalWaitingTime = 0.0;
for(int i = 0; i < size; i++) {
int arrival = customers[i][0];
int time = customers[i][1];
currentTime = currentTime < arrival ? arrival : currentTime;
currentTime += time;
totalWaitingTime += currentTime - arrival;
}
return totalWaitingTime / size;
}
int main() {
int customers[][2] = {{1,2},{2,5},{4,3}};
int size = 3;
printf("%.5f\n", averageWaitingTime(customers, size));
return 0;
}using System;
using System.Collections.Generic;
public class AverageWaitingTime {
public static double ComputeAverageWaitingTime(List<int[]> customers) {
int currentTime = 0;
double totalWaitingTime = 0.0;
foreach(var customer in customers) {
int arrival = customer[0];
int time = customer[1];
currentTime = Math.Max(currentTime, arrival) + time;
totalWaitingTime += currentTime - arrival;
}
return totalWaitingTime / customers.Count;
}
public static void Main() {
var customers = new List<int[]> { new int[] {1, 2}, new int[] {2, 5}, new int[] {4, 3} };
Console.WriteLine(ComputeAverageWaitingTime(customers).ToString("F5"));
}
}The Python function works by iterating each order, computing the waiting times using inline tuple unpacking for efficiency, accumulating total time, and then returning the average.
Time Complexity: O(n) since it processes each customer once.
Space Complexity: O(1) using only a constant amount of space.
Approach 2: Approach 2: Event Simulation with Priority Queue
In scenarios with dynamic restaurant workflows, using event simulation with a priority queue could be beneficial. Here, though all customers wait in order, this method can plan for potential future complexity.
This approach is more efficient when prioritizing different jobs based on arrival or cooking time in expanded contexts.
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
float averageWaitingTime(std::vector<std::pair<int,int>>& customers) {
int currentTime = 0;
float totalWaitingTime = 0.0;
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> pq;
for(auto& customer : customers) {
pq.push(customer);
}
while (!pq.empty()) {
auto customer = pq.top(); pq.pop();
int arrival = customer.first;
int time = customer.second;
currentTime = std::max(currentTime, arrival) + time;
totalWaitingTime += currentTime - arrival;
}
return totalWaitingTime / customers.size();
}
int main() {
std::vector<std::pair<int, int>> customers = {{1,2},{2,5},{4,3}};
std::cout << std::fixed << std::setprecision(5) << averageWaitingTime(customers) << std::endl;
return 0;
}This C++ solution utilizes a priority queue, simulating an event-driven strategy. Although it prioritizes emissions less efficiently for this fixed input, the template demonstrates adaptability for more assorted queues and orders beyond the current sorting constraints.
Time Complexity: O(n log n) due to priority queue operations.
Space Complexity: O(n) for the queue population.
Approach 3: Simulation
We use a variable tot to record the total waiting time of the customers, and a variable t to record the time when each customer's order is completed. The initial values of both are 0.
We traverse the customer array customers. For each customer:
If the current time t is less than or equal to the customer's arrival time customers[i][0], it means that the chef is not cooking, so the chef can start cooking immediately. The time to complete this dish is t = customers[i][0] + customers[i][1], and the customer's waiting time is customers[i][1].
Otherwise, it means that the chef is cooking, so the customer needs to wait for the chef to finish the previous dishes before starting to cook their own dishes. The time to complete this dish is t = t + customers[i][1], and the customer's waiting time is t - customers[i][0].
The time complexity is O(n), where n is the length of the customer array customers. The space complexity is O(1).
function averageWaitingTime(customers: number[][]): number {
let [tot, t] = [0, 0];
for (const [a, b] of customers) {
t = Math.max(t, a) + b;
tot += t - a;
}
return tot / customers.length;
}func averageWaitingTime(customers [][]int) float64 {
tot, t := 0, 0
for _, e := range customers {
a, b := e[0], e[1]
t = max(t, a) + b
tot += t - a
}
return float64(tot) / float64(len(customers))
}impl Solution {
pub fn average_waiting_time(customers: Vec<Vec<i32>>) -> f64 {
let mut tot = 0.0;
let mut t = 0;
for e in customers.iter() {
let a = e[0];
let b = e[1];
t = t.max(a) + b;
tot += (t - a) as f64;
}
tot / customers.len() as f64
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Straightforward Simulation | Time Complexity: O(n) since it processes each customer once. |
| Approach 2: Event Simulation with Priority Queue | Time Complexity: O(n log n) due to priority queue operations. |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Straightforward Simulation | O(n) | O(1) | Best choice for the problem since customers are already ordered by arrival time |
| Event Simulation with Priority Queue | O(n log n) | O(n) | Useful when modeling more complex scheduling such as multiple chefs or dynamic events |
Frequently asked questions
Is Average Waiting Time easy or hard?
Average Waiting Time is rated Medium on LeetCode but conceptually straightforward once you model the timeline correctly. The main challenge is recognizing that the chef may be idle between customers and using max(currentTime, arrivalTime) to handle that case.
Average Waiting Time Python/Java solution
Both Python and Java implementations follow the same idea: iterate through the customers array, track the chef's current time, compute each order's finish time, and accumulate waiting times. The final result is the total waiting time divided by the number of customers.
How to solve Average Waiting Time in O(n)?
Maintain a variable representing when the chef is free. For each customer, compute startTime = max(currentTime, arrivalTime) and finishTime = startTime + cookTime. Add finishTime - arrivalTime to the total waiting time and update currentTime to finishTime. Divide the total by the number of customers at the end.
What is the best approach for Average Waiting Time?
The optimal approach is a straightforward simulation of the restaurant timeline. Track when the chef becomes available and start each order at max(currentTime, arrivalTime). This processes every customer once, giving O(n) time complexity and O(1) extra space.
Is Average Waiting Time asked at Google/Amazon/Meta?
Problems involving queue processing and timeline simulation frequently appear in interviews at companies like Amazon and Google. This problem specifically tests reasoning about event timing, sequential processing, and translating real-world workflows into code.
What data structure is used in Average Waiting Time?
The optimal solution only requires variables and iteration over an array. No additional data structure is needed because customers are already ordered by arrival time. A priority queue can be used in a generalized event-driven simulation version.
What is the time complexity of Average Waiting Time?
The optimal solution runs in O(n) time because you iterate through the customer list exactly once. Each step performs constant-time arithmetic to compute start time, finish time, and waiting time. Space complexity remains O(1).
