Leetcode 1701: Average Waiting Time

grid47
grid47
Exploring patterns and algorithms
May 20, 2024 6 min read

A restaurant with a single chef serves customers. Each customer arrives at a specific time and waits for the chef to prepare their order. The chef can only serve one customer at a time and prepares orders in the order they were received. The goal is to calculate the average waiting time of all customers. The waiting time of a customer is the time between their arrival and when they receive their order.
Problem
Approach
Steps
Complexity
Input: You are given a 2D array where each entry represents a customer, with the first value indicating the arrival time and the second value indicating the time required to prepare the order.
Example: [[1, 2], [3, 4], [6, 1]]
Constraints:
• 1 <= customers.length <= 10^5
• 1 <= arrivali, timei <= 10^4
• arrivali <= arrivali+1
Output: The output is a floating-point number representing the average waiting time for all customers.
Example: 3.33333
Constraints:
• The result must be accurate within 10^-5
Goal: To calculate the average waiting time of all customers.
Steps:
• 1. Initialize the current time to the arrival time of the first customer.
• 2. For each customer, check if the chef is idle or still working on a previous order.
• 3. If the chef is idle, the chef starts preparing the order immediately; otherwise, the chef waits for the chef to finish the current order.
• 4. Add the waiting time (current time - arrival time) to the total waiting time.
• 5. After processing all customers, return the total waiting time divided by the number of customers.
Goal: Ensure that the solution adheres to the constraints to avoid performance issues, especially with large inputs.
Steps:
• The solution should handle up to 100,000 customers efficiently.
Assumptions:
• The customer arrival times are provided in non-decreasing order.
• The chef serves customers in the order they arrive.
Input: [[1, 2], [2, 5], [4, 3]]
Explanation: In this example, the first customer arrives at time 1 and waits 2 units of time, so their waiting time is 2. The second customer arrives at time 2 but waits until the chef is free at time 3, so their waiting time is 6. The third customer arrives at time 4 and waits until the chef is free at time 8, giving them a waiting time of 7. The average waiting time is (2 + 6 + 7) / 3 = 5.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus