Shortest Job First

Asked atSalesforce
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

A software engineer is tasked with using the shortest job first (SJF) policy to calculate the average waiting time for each process. The shortest job first also known as shortest job next (SJN) scheduling policy selects the waiting process with the least execution time to run next.

You are given an array of integers **bt **of size n representing the **burst times (execution times) **of n processes.

Your task is to calculate the average waiting time for all processes when scheduled using the SJF policy. The waiting time of a process is the total time a process has to wait before its execution starts, which is the sum of burst times of all previously executed processes.

Return the floor of the average waiting time, i.e., the largest whole number less than or equal to the actual average.

Input : bt = [4, 1, 3, 7, 2] Output : 4 Explanation : The total waiting time is 20. So the average waiting time will be 20/5 => 4.

Input : bt = [1, 2, 3, 4] Output : 2 Explanation : The total waiting time is 10. So the average waiting time will be 10/4 => 2.

Input : bt = [9, 3, 1, 8, 2]

  • 1 <= n <= 105
  • 1 <= bt[i] <= 105

cpp

class Solution {
  public:
    long long solve(vector<int>& bt) {
        //your code goes here
    }
};

java

class Solution {
    public long solve(int[] bt) {
        //your code goes here
    }
}

python

class Solution:
    def solve(self, bt):
        #your code goes here

javascript

class Solution {
    solve(bt) {
        //your code goes here
    }
}

csharp

public class Solution
{
    public long Solve(List<int> bt)
    {
        //your code goes here
    }
}

go

func solve(bt []int) int64 {
	//your code goes here
}
Stuck? Show a way to structure it+
  1. 01Clarify preemptive versus non-preemptive and arrival assumptions
  2. 02Sort durations if all arrive together
  3. 03Accumulate elapsed time and waiting-time total
  4. 04For arrivals, push available jobs into a min-heap

Reference answer

Then expect these follow-ups

  • How does shortest remaining time first differ?

    Tests: complexity analysis

  • Can starvation occur?

    Tests: follow-up reasoning

Hiring now

Salesforce has 1,420 open roles right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Business Development Representative Belgium Market (Dutch Speaking)

    Ireland - Dublin

  • Service Cloud Account Executive

    France - Paris

  • Summer Intern 2027 - Content Writer

    India - Bangalore

Or practice this question first

Next question