DSA Factory
Free Greedy lessonsGreedy · Stage 3 · Exchange arguments · Step 1

Shortest job first

Serve customers in the order that makes the total waiting time smallest, and see why swapping two neighbours proves the order is best. About 15 minutes.

Who waits for whom

A single counter serves customers one at a time. Each customer needs some minutes. A customer waits for everyone served before them, not for their own service.

So the first job in the line is waited on by every later customer, the second by all but one, and so on. A long job early is paid for many times. A short job early is paid for cheaply.

Early jobs: are waited on by many customers.
Put short jobs early: so fewer minutes are repeated.

The exchange argument

Why is shortest first really best? Take any order where a long job L is served right before a short job S. Swap them.

Everyone else waits the same, since the pair still takes L plus S together. The job S now waits less, because it no longer waits for L, while L waits only a little more. The total never rises. Repeat swaps until no long job sits before a short one: that is the sorted order.

Swap a long-short pair, the total wait does not go up.
Sorted order: is what remains when no swaps are left.
In code
order = sorted(times)
running = 0
for t in order:
    running += t
Service times sorted: 1, 3, 4. The wait before each job is the sum of the jobs before it.
1
0
3
1
4
2
i

The first customer waits 0. Total wait 0.

Move 1 of 3
Quick check

Jobs take 4 and 1 minutes. Which order gives the smaller total wait?

  1. A1 first, then 4 (total wait 1)
  2. B4 first, then 1 (total wait 4)
  3. CBoth orders give the same total
Show the answer

1 first, then 4 (total wait 1). The second job waits 1 minute, and the first waits 0.

Your problem

Least total waiting time

Customers arrive at a counter together, and you are given the minutes each one needs in an array times. The counter serves one customer at a time. A customer's waiting time is the minutes they wait before their own service starts. Return the smallest possible total waiting time of all customers.

Example
times = [3, 2, 5] → 7

0 ≤ times.length ≤ 100,000 · 1 ≤ times[i] ≤ 1,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve