You are given an array bt where bt[i] is the burst time (CPU time needed) of process i. Using non-preemptive Shortest Job First (SJF) scheduling, compute the average waiting time across all processes and return its floor (integer part).
A process's waiting time is how long it sits before it starts running — the total burst time of every process scheduled ahead of it.
Input: bt = [4, 3, 7, 1, 2] Output: 4 Sorted bursts 1,2,3,4,7 give waiting times 0,1,3,6,10; average = 20 / 5 = 4.
Input: bt = [1, 2, 3] Output: 1 Waiting times 0,1,3 sum to 4; 4 / 3 floors to 1.
- 1 <= bt.length <= 10^4 - 1 <= bt[i] <= 10^5
To make everyone wait as little as possible on average, run the shortest jobs first. A long job scheduled early makes every job behind it wait longer, so pushing it to the back minimizes the total (and hence average) waiting time. Once the order is fixed, the waiting times are just prefix sums.
“Is scheduling preemptive?”
No — once a job starts it runs to completion, so order is decided up front.
“Do all jobs arrive at time 0?”
Yes — this is the classic SJF where only burst times matter.
“Average of what, exactly?”
The waiting times — each job's delay before it starts — averaged and floored.
Average waiting time is minimized by running the shortest jobs first.
After sorting ascending, each job's wait is the sum of all burst times before it — a prefix sum.
I keep a running total of those prefix sums and divide by n at the end.
Worked example — bt = [4, 3, 7, 1, 2]
sorted: 1 2 3 4 7 waits: 0 1 3 6 10 (each = running sum of earlier bursts) total waiting = 20 average = 20 / 5 = 4
A job of length L delays every job scheduled after it by L. Placing short jobs first means fewer jobs are delayed by the long ones — provably the minimum total (and average) waiting time.
After sorting, job i's waiting time is bt[0] + ... + bt[i-1]. So the total waiting time is the sum of all prefix sums — computable in one pass with a running accumulator.
Keep wait (the next job's waiting time) and add it to total before extending it by the current burst. That turns an O(n^2) double sum into a single O(n) sweep.
| Sum each prefix | Running prefix | |
|---|---|---|
| Idea | For each job, re-add all earlier burst times | Carry a running waiting time as you sweep |
| Time | O(n^2) after sort | O(n log n) (the sort) |
| Space | O(1) | O(1) |
Both sort first; the optimal just avoids recomputing each prefix from scratch. Full code is in the Approaches selector below.
Key takeaway
Sort burst times ascending (shortest job first), then each job's waiting time is the prefix sum of the bursts before it. Accumulate those with one running total and divide by n. Shortest-first is optimal because a long job early delays everyone behind it.
sort bt ascending
total = 0; wait = 0
for x in bt:
total += wait # this job waits for all earlier ones
wait += x # future jobs also wait for this one
return floor(total / n)