AlgoFrames

Simulate SJF in code

Challenge · Write code · about 20 min

Process i arrives at arrival[i] and needs burst[i] units of CPU. Non-preemptive shortest job first works like this: whenever the CPU is free, it starts the ready process with the shortest burst and runs it to completion. A process is ready once its arrival time has passed. If nobody is ready, the CPU idles until the next arrival.

Return the total waiting time over all processes (start − arrival, summed).

Example 1

Input:

[[0,2,4],[7,4,1]]

Output:

9

P0 is alone at time 0, so it runs first even though it is the longest.

Example 2

Input:

[[0,0,0],[8,4,2]]

Output:

8

Order P2, P1, P0: waits 0, 2 and 6.

Constraints

  • 1 ≤ n ≤ 1,000, where n = arrival.length = burst.length
  • 0 ≤ arrival[i] ≤ 1,000
  • 1 ≤ burst[i] ≤ 100
  • The answer fits in a 32-bit integer

Learn the idea first: CPU scheduling: FCFS, SJF, priority, round robin, a visual lesson.

More CPU scheduling: FCFS, SJF, priority, round robin problems