Shortest Job First

Pattern: Activity selection

medium

With every job arriving at time 0 and one processor, run the shortest job first. Each job waits for the sum of the jobs before it, so putting short jobs early keeps every later wait small. Return the average wait, rounded down.

The problem

Jobs with the given burst times all arrive at time 0 and run one at a time, without being interrupted. Order them to make the average waiting time as small as possible and return that average, rounded down. [4, 3, 7, 1, 2] gives 4.

The linked GFG page also gives each job an arrival time; this guide's version, like takeUforward's, has every job arrive at 0.

Think first

  • How long does the k-th job wait?
  • What happens to the total if a long job runs before a short one?
  • So which order is best?

Hints

    Brute force, and why it fails

    Try every order: O(n!).

    The key insight

    A job's length is added to the wait of every job after it, so the longest jobs should have the fewest jobs after them: sort ascending.

    Dry run

    10 
    21 
    32 
    43 
    74 

    bt = [4, 3, 7, 1, 2]. Sorted: 1, 2, 3, 4, 7.

    Step 1 of 3

    The plan

    sort bt
    elapsed = 0; total = 0
    for b in bt: total += elapsed; elapsed += b
    return total / n (rounded down)
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    Sorting dominates; the copy keeps the input unchanged.

    Edge cases

    • One job: 0.
    • Equal jobs: order does not matter.
    • Large totals: use 64-bit sums.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int solve(int[] bt) {
            int[] jobs = bt.clone();
            Arrays.sort(jobs);                      // shortest first keeps everyone's wait smallest
            long elapsed = 0, totalWait = 0;
            for (int b : jobs) {
                totalWait += elapsed;               // this job waited for everything before it
                elapsed += b;
            }
            return (int) (totalWait / jobs.length); // whole-number average, rounded down
        }
    }

    C++

    class Solution {
    public:
        int solve(vector<int>& bt) {
            vector<int> jobs(bt);
            sort(jobs.begin(), jobs.end());         // shortest first keeps everyone's wait smallest
            long long elapsed = 0, totalWait = 0;
            for (int b : jobs) {
                totalWait += elapsed;               // this job waited for everything before it
                elapsed += b;
            }
            return static_cast<int>(totalWait / static_cast<long long>(jobs.size()));   // rounded down
        }
    };

    Python

    class Solution:
        def solve(self, bt: list[int]) -> int:
            elapsed = total_wait = 0
            for b in sorted(bt):                    # shortest first keeps everyone's wait smallest
                total_wait += elapsed               # this job waited for everything before it
                elapsed += b
            return total_wait // len(bt)            # whole-number average, rounded down

    Common mistakes

    • Adding the job's own time to its wait.
    • Rounding the average up.

    Similar problems