Shortest Job First

easy

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.

Hints

To minimize average waiting time, in what order should the jobs run?
Run the shortest jobs first — a long job early delays everyone behind it.
After sorting, each job's waiting time is the running sum of the burst times before it.

Common doubts

A job of length L adds L to the waiting time of every job after it. Scheduling short jobs first means the large delays are shared by the fewest remaining jobs.
The problem asks for the integer part of the average waiting time, so integer (floor) division of the total by n is exactly what's required.
Yes for large inputs — the total waiting time is a sum of prefix sums and can exceed a 32-bit range, so accumulate it in a 64-bit integer.

Interview follow-ups

Then it becomes SJF with arrivals — at each completion you pick the shortest job that has arrived, typically maintained with a min-heap keyed on burst time.
Turnaround = waiting + burst, so add each job's own burst to its waiting time before averaging.

Fun facts

  • SJF provably minimizes average waiting time among all non-preemptive schedules — but it needs to know burst times in advance, which real schedulers must estimate.
  • The 'shortest first' rule is the same intuition behind serving quick tasks before slow ones at any queue or checkout.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
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.
Example 2
Input: bt = [1, 2, 3]
Output: 1
Waiting times 0,1,3 sum to 4; 4 / 3 floors to 1.
Constraints

- 1 <= bt.length <= 10^4 - 1 <= bt[i] <= 10^5

Solve this problem →