Single-Threaded CPU

Medium Heaps Composite comparator

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.length
  • 1 <= n <= 10^5
  • tasks[i].length == 2
  • 1 <= 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.

00:00
Testcase

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.

ApproachTimeSpace
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)

TimeO(n^2)Each of the n picks scans all n tasks twice.
SpaceO(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.

  1. Keep time = 0, a done flag per task and the answer array.
  2. For each of the n picks, find the earliest enqueue time among unfinished tasks and set time = max(time, earliest). This skips idle stretches.
  3. 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.
  4. 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;
    }
}

2Optimal (sort by arrival + min-heap of waiting tasks)

TimeO(n log n)Sorting is O(n log n), and each task is pushed once and polled once, O(log n) each.
SpaceO(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.

  1. Sort the indices 0..n-1 by enqueue time. Set time = 0 and a pointer next = 0 into that sorted list.
  2. 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).
  3. While next < n and the task at next has enqueue time <= time, push it into the heap and advance next.
  4. 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;
    }
}

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.