#1701

Average Waiting Time

Medium
ArraySimulationSimulationGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution efficiently calculates the average waiting time by tracking when the chef is free and when each customer arrives. It avoids unnecessary checks and directly computes waiting times in a single pass through the customers.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize total waiting time and current time to 0.
  2. 2Step 2: Iterate through each customer in the list.
  3. 3Step 3: If the chef is free (current time < arrival), set current time to the customer's arrival time.
  4. 4Step 4: Calculate the waiting time for the customer and add it to the total waiting time. Update the current time by adding the preparation time of the customer.
  5. 5Step 5: After processing all customers, return the average waiting time.
solution.py8 lines
1def averageWaitingTime(customers):
2    total_waiting_time = 0
3    current_time = 0
4    for arrival, time in customers:
5        current_time = max(current_time, arrival)
6        total_waiting_time += current_time - arrival + time
7        current_time += time
8    return total_waiting_time / len(customers)

Complexity note: This complexity is linear because we only make a single pass through the list of customers, performing constant time operations for each customer.

  • 1Understanding how to track time is crucial in simulation problems.
  • 2Using max(current_time, arrival) helps to efficiently manage waiting times.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.