Single-Threaded CPU
Single-Threaded CPU is a medium heaps problem solved with the composite comparator pattern.
The best approach, optimal (sort by arrival + min-heap of waiting tasks), runs in O(n log n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (scan every task at each pick) up.
Problem
You are given n tasks, numbered 0 to n - 1, as a 2D array tasks, where tasks[i] = [enqueueTime_i, processingTime_i]. Task i becomes available at time enqueueTime_i and needs processingTime_i units of time to finish.
A single CPU runs the tasks, one at a time, by these rules:
- When the CPU is idle and no task is available, it stays idle.
- When the CPU is idle and at least one task is available, it starts the available task with the shortest processing time. If several are tied, it picks the one with the smallest index.
- Once a task starts, it runs to the end without interruption. The CPU can start the next task at the very moment the current one finishes.
Return the order in which the CPU processes the tasks, as a list of task indices.
Examples
Example 1
- Input
tasks = [[2,3],[4,1],[3,2],[6,4],[7,1]]- Output
[0,1,2,4,3]- Why
- Task 0 arrives at time 2 and runs until 5. At 5, tasks 1 (length 1) and 2 (length 2) are waiting, so task 1 runs until 6. At 6, tasks 2 and 3 are waiting; task 2 is shorter and runs until 8. At 8, task 4 (length 1) beats task 3 (length 4), and task 3 goes last.
Example 2
- Input
tasks = [[5,3],[5,1],[5,3],[5,2]]- Output
[1,3,0,2]- Why
- All four tasks arrive together. They run shortest first: task 1, then task 3. Tasks 0 and 2 have the same length, so the smaller index, 0, goes first.
Example 3
- Input
tasks = [[10,2],[1,5],[20,1]]- Output
[1,0,2]- Why
- Task 1 runs from 1 to 6. The CPU then sits idle until task 0 arrives at 10 and runs until 12, and idles again until task 2 arrives at 20.
Constraints
n == tasks.length1 <= n <= 10^5tasks[i].length == 21 <= enqueueTime_i, processingTime_i <= 10^9
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (scan every task at each pick) | O(n^2) | O(n) |
| Optimal (sort by arrival + min-heap of waiting tasks) | O(n log n) | O(n) |
1Brute force (scan every task at each pick)
O(n^2)Each of the n picks scans all n tasks twice.O(n)The done flags and the answer array.Run the clock directly. Every time the CPU is free, look through all unfinished tasks and pick the one it should run next: among those that have arrived, the shortest, with the smaller index on a tie. If none has arrived yet, the CPU is idle, so first move the clock forward to the earliest arrival among the unfinished tasks.
- Keep time = 0, a done flag per task and the answer array.
- For each of the n picks, find the earliest enqueue time among unfinished tasks and set time = max(time, earliest). This skips idle stretches.
- Scan the tasks in index order and keep the unfinished, arrived task with the smallest processing time. A strict less-than keeps the smaller index on ties.
- Mark it done, append its index, and add its processing time to the clock.
class Solution {
public int[] getOrder(int[][] tasks) {
int n = tasks.length;
boolean[] done = new boolean[n];
int[] order = new int[n];
long time = 0;
for (int k = 0; k < n; k++) {
long earliest = Long.MAX_VALUE;
for (int i = 0; i < n; i++)
if (!done[i]) earliest = Math.min(earliest, tasks[i][0]);
time = Math.max(time, earliest);
int pick = -1;
for (int i = 0; i < n; i++) {
if (done[i] || tasks[i][0] > time) continue;
if (pick == -1 || tasks[i][1] < tasks[pick][1]) pick = i;
}
done[pick] = true;
order[k] = pick;
time += tasks[pick][1];
}
return order;
}
}class Solution:
def getOrder(self, tasks: List[List[int]]) -> List[int]:
n = len(tasks)
done = [False] * n
order = [0] * n
time = 0
for k in range(n):
earliest = min(tasks[i][0] for i in range(n) if not done[i])
time = max(time, earliest)
pick = -1
for i in range(n):
if done[i] or tasks[i][0] > time:
continue
if pick == -1 or tasks[i][1] < tasks[pick][1]:
pick = i
done[pick] = True
order[k] = pick
time += tasks[pick][1]
return orderclass Solution {
public:
vector<int> getOrder(vector<vector<int>>& tasks) {
int n = tasks.size();
vector<bool> done(n, false);
vector<int> order(n);
long long time = 0;
for (int k = 0; k < n; k++) {
long long earliest = LLONG_MAX;
for (int i = 0; i < n; i++)
if (!done[i]) earliest = min(earliest, (long long)tasks[i][0]);
time = max(time, earliest);
int pick = -1;
for (int i = 0; i < n; i++) {
if (done[i] || tasks[i][0] > time) continue;
if (pick == -1 || tasks[i][1] < tasks[pick][1]) pick = i;
}
done[pick] = true;
order[k] = pick;
time += tasks[pick][1];
}
return order;
}
};function getOrder(tasks) {
const n = tasks.length;
const done = new Array(n).fill(false);
const order = new Array(n).fill(0);
let time = 0;
for (let k = 0; k < n; k++) {
let earliest = Infinity;
for (let i = 0; i < n; i++)
if (!done[i]) earliest = Math.min(earliest, tasks[i][0]);
time = Math.max(time, earliest);
let pick = -1;
for (let i = 0; i < n; i++) {
if (done[i] || tasks[i][0] > time) continue;
if (pick === -1 || tasks[i][1] < tasks[pick][1]) pick = i;
}
done[pick] = true;
order[k] = pick;
time += tasks[pick][1];
}
return order;
}2Optimal (sort by arrival + min-heap of waiting tasks)
O(n log n)Sorting is O(n log n), and each task is pushed once and polled once, O(log n) each.O(n)The sorted index array and the heap hold at most n entries.Two questions repeat at every pick: which tasks have arrived by now, and which of them is shortest. Sorting the task indices by enqueue time answers the first with a single pointer that only moves forward: everything before it has arrived. A min-heap keyed by (processing time, index) answers the second in O(log n). When the heap is empty the CPU is idle, so the clock jumps straight to the next arrival.
- Sort the indices 0..n-1 by enqueue time. Set time = 0 and a pointer next = 0 into that sorted list.
- Loop until n tasks are in the answer. If the heap is empty and the next task has not arrived yet, set time to its enqueue time (the idle jump).
- While next < n and the task at next has enqueue time <= time, push it into the heap and advance next.
- Poll the heap's top: the shortest waiting task, smaller index on a tie. Append its index and add its processing time to the clock.
class Solution {
public int[] getOrder(int[][] tasks) {
int n = tasks.length;
Integer[] idx = new Integer[n];
for (int i = 0; i < n; i++) idx[i] = i;
Arrays.sort(idx, (a, b) -> Integer.compare(tasks[a][0], tasks[b][0]));
PriorityQueue<Integer> ready = new PriorityQueue<>(
(a, b) -> tasks[a][1] != tasks[b][1] ? Integer.compare(tasks[a][1], tasks[b][1]) : Integer.compare(a, b));
int[] order = new int[n];
long time = 0;
int next = 0, k = 0;
while (k < n) {
if (ready.isEmpty() && time < tasks[idx[next]][0]) time = tasks[idx[next]][0];
while (next < n && tasks[idx[next]][0] <= time) ready.offer(idx[next++]);
int cur = ready.poll();
order[k++] = cur;
time += tasks[cur][1];
}
return order;
}
}class Solution:
def getOrder(self, tasks: List[List[int]]) -> List[int]:
n = len(tasks)
idx = sorted(range(n), key=lambda i: tasks[i][0])
ready = []
order = []
time = 0
nxt = 0
while len(order) < n:
if not ready and time < tasks[idx[nxt]][0]:
time = tasks[idx[nxt]][0]
while nxt < n and tasks[idx[nxt]][0] <= time:
heapq.heappush(ready, (tasks[idx[nxt]][1], idx[nxt]))
nxt += 1
proc, cur = heapq.heappop(ready)
order.append(cur)
time += proc
return orderclass Solution {
public:
vector<int> getOrder(vector<vector<int>>& tasks) {
int n = tasks.size();
vector<int> idx(n);
for (int i = 0; i < n; i++) idx[i] = i;
sort(idx.begin(), idx.end(), [&](int a, int b) { return tasks[a][0] < tasks[b][0]; });
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> ready;
vector<int> order;
long long time = 0;
int next = 0;
while ((int)order.size() < n) {
if (ready.empty() && time < tasks[idx[next]][0]) time = tasks[idx[next]][0];
while (next < n && tasks[idx[next]][0] <= time) {
ready.push({tasks[idx[next]][1], idx[next]});
next++;
}
auto [proc, cur] = ready.top();
ready.pop();
order.push_back(cur);
time += proc;
}
return order;
}
};class MinHeap {
constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
size() { return this.a.length; }
isEmpty() { return this.a.length === 0; }
peek() { return this.a[0]; }
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (this.cmp(a[i], a[p]) >= 0) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}
function getOrder(tasks) {
const n = tasks.length;
const idx = Array.from({ length: n }, (_, i) => i);
idx.sort((a, b) => tasks[a][0] - tasks[b][0]);
const ready = new MinHeap((a, b) => tasks[a][1] !== tasks[b][1] ? tasks[a][1] - tasks[b][1] : a - b);
const order = [];
let time = 0, next = 0;
while (order.length < n) {
if (ready.isEmpty() && time < tasks[idx[next]][0]) time = tasks[idx[next]][0];
while (next < n && tasks[idx[next]][0] <= time) ready.push(idx[next++]);
const cur = ready.pop();
order.push(cur);
time += tasks[cur][1];
}
return order;
}Edge cases to test
- A single task: the answer is [0]
- Every task arrives at the same moment: the order is simply by length, then by index
- Two waiting tasks with the same length: the smaller index runs first
- The CPU goes idle: when nothing is waiting, the clock jumps to the next arrival instead of ticking one unit at a time
- A task that arrives exactly when the CPU finishes is already waiting at that moment
- A short task that arrives later never interrupts a long task that is already running
- Times add up past the int range (10^5 tasks of length 10^9), so keep the clock in a long
Hints
Hint 1
Simulate the CPU with a clock. Each time it becomes free, which tasks can it choose from, and which one does it pick?
Hint 2
Sort the tasks by arrival time, so that the tasks which have arrived by the current time are always a prefix of the sorted list.
Hint 3
Keep the arrived but unfinished tasks in a min-heap ordered by (processing time, index). When the heap is empty, jump the clock to the next arrival.
FAQ
What is the best time complexity for Single-Threaded CPU?
Optimal (sort by arrival + min-heap of waiting tasks) runs in O(n log n) time and O(n) extra space. Sorting is O(n log n), and each task is pushed once and polled once, O(log n) each.
Which pattern does Single-Threaded CPU use?
It is a heaps problem that uses the composite comparator pattern. Other problems with the same pattern: Top K Frequent Elements, Design Task Manager, Rank Teams by Votes.
Is there a brute force solution for Single-Threaded CPU?
Yes. Brute force (scan every task at each pick) takes O(n^2) time and O(n) space. Run the clock directly.
Which edge cases should I test for Single-Threaded CPU?
A single task: the answer is [0]; Every task arrives at the same moment: the order is simply by length, then by index; Two waiting tasks with the same length: the smaller index runs first; The CPU goes idle: when nothing is waiting, the clock jumps to the next arrival instead of ticking one unit at a time; A task that arrives exactly when the CPU finishes is already waiting at that moment; A short task that arrives later never interrupts a long task that is already running; Times add up past the int range (10^5 tasks of length 10^9), so keep the clock in a long.