Single-Threaded CPU solution explained
Single-Threaded CPU asks in which order one processor finishes a list of tasks, when each task becomes available at a given time and the processor, whenever it is free, starts the shortest available task (ties go to the lowest index). Sort the tasks by arrival, keep a min-heap of available tasks keyed by (duration, index), and when the heap is empty jump the clock to the next arrival. That runs in O(n log n).
By Evin JohnPublished 8 min read
The problem, in plain terms
You get n tasks, numbered 0 to n - 1. Task i has an arrival time and a duration. One processor handles them under three rules. When it is free and at least one task has arrived and not started, it starts the one with the shortest duration, and among equal durations the one with the smallest index. Once a task starts, it runs to completion. When it is free and no task is waiting, it does nothing until the next task arrives. Return the indexes in the order the processor runs them.
index 0 1 2 3 4
arrival 2 0 1 14 2
duration 3 4 1 2 1
time 0 only task 1 has arrived run 1, busy until 4
time 4 tasks 0, 2, 4 are waiting run 2 (duration 1, lower index than 4), until 5
time 5 tasks 0, 4 are waiting run 4, until 6
time 6 task 0 is waiting run 0, until 9
time 9 nothing waiting, task 3 at 14 idle, jump to 14, run 3, until 16
order: [1, 2, 4, 0, 3]Two details carry most of the difficulty. At time 4, tasks 2 and 4 both last 1, so the index breaks the tie. At time 9 the waiting set is empty, and the clock has to jump to the next arrival rather than tick forward one unit at a time, which would be far too slow when times are large.
Clarify before coding: does a task that arrives at exactly the moment the processor frees up count as available? (Here it does.) How large can arrival times and durations get, and can their sum overflow a 32-bit integer? Is the order by index stable when two tasks have the same duration and arrival? The tie rule says it is.
Why it is asked
This is a scheduling simulation, a type that shows up often because it tests several things at once: sorting by one key while choosing by another, using a priority queue with a compound key, and handling idle time without a busy loop. Bugs in these problems tend to come from the event loop, not from the heap, so interviewers watch how you structure the loop and whether you test the idle gap.
Brute force: scan for the next task
Keep a set of tasks not yet run. Each time the processor is free, look through all of them for arrived tasks and take the best by (duration, index). If none has arrived, set the clock to the smallest arrival among the remaining tasks. Every pick scans all remaining tasks, so this is O(n²), but it states the rules so directly that it is the reference everything else was checked against.
def cpu_order_slow(tasks):
left = set(range(len(tasks)))
clock, order = 0, []
while left:
ready = [i for i in left if tasks[i][0] <= clock]
if not ready:
clock = min(tasks[i][0] for i in left)
continue
pick = min(ready, key=lambda i: (tasks[i][1], i))
left.remove(pick)
order.append(pick)
clock += tasks[pick][1]
return orderOptimal approach: sort by arrival, heap by duration
Arrivals are known in advance, so sort the indexes by arrival time once and walk them with a pointer. Keep a min-heap of tasks that have arrived but not run, keyed by (duration, index). The loop is: if the heap is empty, move the clock forward to the next arrival. Push every task whose arrival is at or before the clock. Pop the top, record it, and add its duration to the clock. Each task is pushed and popped once.
import heapq
def cpu_order(tasks):
by_arrival = sorted(range(len(tasks)), key=lambda i: tasks[i][0])
ready, order = [], []
clock, nxt = 0, 0
while len(order) < len(tasks):
if not ready and clock < tasks[by_arrival[nxt]][0]:
clock = tasks[by_arrival[nxt]][0] # idle until the next arrival
while nxt < len(tasks) and tasks[by_arrival[nxt]][0] <= clock:
i = by_arrival[nxt]
heapq.heappush(ready, (tasks[i][1], i))
nxt += 1
duration, i = heapq.heappop(ready)
order.append(i)
clock += duration
return orderThe idle jump only happens when the heap is empty, and then at least one task has not arrived yet, so by_arrival[nxt] is always a valid index at that point. Tuples compare element by element, so (duration, index) gives the tie rule for free.
In C++, std::priority_queue is a max-heap by default, so pass std::greater to turn it into a min-heap over pairs. Use long long for the clock: a long chain of long tasks can push it past what a 32-bit int holds.
#include <algorithm>
#include <functional>
#include <numeric>
#include <queue>
#include <utility>
#include <vector>
std::vector<int> cpuOrder(const std::vector<std::pair<long long, long long>>& tasks) {
int n = tasks.size();
std::vector<int> byArrival(n);
std::iota(byArrival.begin(), byArrival.end(), 0);
std::sort(byArrival.begin(), byArrival.end(),
[&](int a, int b) { return tasks[a].first < tasks[b].first; });
using Item = std::pair<long long, int>; // (duration, index)
std::priority_queue<Item, std::vector<Item>, std::greater<Item>> ready;
std::vector<int> order;
long long clock = 0;
int nxt = 0;
while ((int)order.size() < n) {
if (ready.empty() && clock < tasks[byArrival[nxt]].first)
clock = tasks[byArrival[nxt]].first;
while (nxt < n && tasks[byArrival[nxt]].first <= clock) {
int i = byArrival[nxt++];
ready.push({tasks[i].second, i});
}
auto [duration, i] = ready.top();
ready.pop();
order.push_back(i);
clock += duration;
}
return order;
}Complexity summary
| Approach | Time | Extra memory | Comment |
|---|---|---|---|
| Rescan remaining tasks | O(n²) | O(n) | Clear reference, too slow for large n |
| Sort plus min-heap | O(n log n) | O(n) | Expected answer |
| Tick the clock one unit at a time | O(n log n + total time) | O(n) | Breaks when times are large |
Edge cases to try
- One task: the answer is [0].
- All tasks arrive at time 0: the order is simply by (duration, index).
- A long idle gap between two groups of tasks: the clock must jump, not tick.
- A task arriving exactly when the previous one finishes: it is available at that moment.
- Several tasks with the same duration and arrival: lowest index first.
- Very large arrival times and durations: check for overflow in fixed-width integers.
Mistakes to avoid
- Keying the heap by duration only, so ties come out in an arbitrary order.
- Pushing only one arrived task per loop iteration instead of all of them, which lets a short task be skipped.
- Forgetting the idle jump, which either loops forever or pops from an empty heap.
- Sorting the tasks themselves and losing their original indexes.
- Using int for the clock in C++ or Java when arrivals and durations are large.
Follow-ups
- Two or more processors. Keep a second min-heap of busy processors keyed by the time they become free. When a processor frees up, assign it the best waiting task. That is the structure behind several server-assignment problems.
- Preemption. If a shorter task arrives while one is running, should it interrupt? That is shortest-remaining-time-first; store remaining time in the heap and treat each arrival as an event.
- Report average waiting time. Record start time minus arrival for each task as you pop it.
- Why shortest first at all? When every task is present at the start, running the shortest first minimizes the total waiting time on one processor. The exchange argument: if a longer task runs right before a shorter one, swapping them lowers the wait of one by more than it raises the other.
- Tasks arrive as a live stream. Replace the sorted list with an event queue; the heap logic does not change. For the distributed version of this idea, the job scheduler system design guide is a good next step.
How to explain it out loud
Fictional example
- Candidate
- Two orderings matter: when tasks arrive, which I know up front, and which waiting task runs next. So I sort by arrival once and use a min-heap keyed by duration and then index for the waiting tasks.
- Candidate
- Each round: if nothing is waiting, jump the clock to the next arrival. Push everything that has arrived by now. Pop the best task and advance the clock by its duration.
- Interviewer
- Why not just increment the clock?
- Candidate
- Times can be huge, so ticking could take billions of steps. Jumping keeps the loop at n iterations, and the total is O(n log n).
- Candidate
- Let me trace the case with a gap: after task 0 finishes at 9, the heap is empty and the next arrival is 14, so the clock jumps there and task 3 runs.
Related problems
IPO has the same shape, a list sorted by one key that unlocks items into a heap ordered by another. Furthest Building You Can Reach uses a heap to revise earlier choices as you walk forward. Moving Average from Data Stream and Logger Rate Limiter are the simpler stream simulations. Merge Intervals is a good warm-up for sorting by start time.
Practicing it with Natively
Simulations are easy to get almost right, so it pays to rehearse the trace out loud. During practice on Mac or Windows, Natively can read the task list from a screenshot and sketch the sort-plus-heap loop, and its transcript of your mock session shows whether you tested the idle gap or skipped it. See how practice works on the AI coding interview helper page.
Questions people ask
How do you solve Single-Threaded CPU?
Sort task indexes by arrival time. Keep a min-heap of arrived tasks keyed by (duration, index). Each round, if the heap is empty move the clock to the next arrival, push every task that has arrived, pop the top task, record it and add its duration to the clock.
What is the time complexity of Single-Threaded CPU?
O(n log n): the sort is O(n log n) and each task is pushed and popped from the heap once. Memory is O(n).
How are ties broken in Single-Threaded CPU?
Among available tasks with the same duration, the smallest index runs first. Keying the heap by the pair (duration, index) handles that automatically.
What happens when the CPU is idle in Single-Threaded CPU?
If no task is waiting, the clock jumps straight to the next arrival time. Incrementing it one unit at a time would be far too slow when times are large.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
