PPractick

DSA interview question

Shortest Job First (Average Waiting Time)

Medium · Algorithms · Topics: greedy, sorting

The problem

An operating-systems course simulates a CPU scheduler. n processes all arrive at time 0 with known burst times, and the CPU runs them one at a time, without preemption. A process's waiting time is how long it sits in the queue before starting. Which order minimises the average waiting time, and what is it (rounded down)? Shortest Job First: run the shortest jobs first. Each job's burst delays every job after it, so short jobs should go first.

Example: bursts [4, 3, 7, 1, 2] → 4 (order 1, 2, 3, 4, 7 gives waits 0, 1, 3, 6, 10).

Function signature

long long averageWaitingTime(vector<int> bt);  // floor of the average waiting time

Test cases

InputOutputExplanation
[4, 3, 7, 1, 2]4Total wait 20, divided by 5
[1, 2, 3, 4]210 / 4 = 2.5, rounded down
[2, 2, 2]2Waits 0, 2, 4
[10, 1]0Waits 0, 1: average 0.5
[5]0

(Confirm: all processes arrive at time 0; non-preemptive; the result is the floor of the average.)

How interviewers phrase it

Clarifying questions to ask

  1. Do all processes arrive at time 0? (Yes; different arrival times need a heap-based simulation.)
  2. Preemptive or not? (Non-preemptive.)
  3. How should the average be rounded? (Floor.)

Follow-ups to expect

  1. "Why is SJF optimal for total waiting time?"
  2. "What if processes arrive at different times?"
  3. "Downside of SJF?"
  4. "Turnaround time?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in