sagelearnai

Single-Threaded CPU

Difficulty: Medium · Pattern: Heap & Priority Queue · LeetCode #1834

tasks[i] = [enqueueTime, processingTime]. A single-threaded CPU:

  • When idle with no available tasks, it waits.
  • When idle with available tasks, it picks the one with the shortest processing time, breaking ties by the smallest index.
  • It runs a task to completion without stopping.

Return the order in which the CPU processes the tasks.

Examples

text
[[1,2],[2,4],[3,2],[4,1]]          →  [0,2,3,1]
[[7,10],[7,12],[7,5],[7,4],[7,2]]  →  [4,3,2,0,1]

Hints

  1. Sort the task indices by enqueue time so you can add tasks to a "ready" pool as time advances.
  2. The ready pool is a min-heap keyed on (processingTime, index).
  3. If the pool is empty, jump the clock forward to the next enqueue time.

Approach

This is a simulation with a heap:

text
order = indices sorted by enqueueTime
t = 0, i = 0, heap = []
while len(result) < n:
    if heap is empty and t < enqueue[order[i]]: t = enqueue[order[i]]   # idle jump
    while i < n and enqueue[order[i]] <= t: push (proc, idx); i++
    (p, idx) = pop; t += p; result.append(idx)

The idle jump prevents ticking the clock one unit at a time, which would be O(max time). Each task is pushed and popped once, so the whole run is O(n log n).

Complexity

Time: O(n log n). Space: O(n).

Python solution
import heapq

def getOrder(tasks):
    order = sorted(range(len(tasks)), key=lambda i: tasks[i][0])
    res, heap, t, i, n = [], [], 0, 0, len(tasks)
    while len(res) < n:
        if not heap and t < tasks[order[i]][0]:
            t = tasks[order[i]][0]
        while i < n and tasks[order[i]][0] <= t:
            j = order[i]
            heapq.heappush(heap, (tasks[j][1], j))
            i += 1
        p, j = heapq.heappop(heap)
        t += p
        res.append(j)
    return res
JavaScript solution
function getOrder(tasks) {
  const n = tasks.length;
  const order = [...tasks.keys()].sort((a, b) => tasks[a][0] - tasks[b][0]);
  const heap = [];
  const less = (a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);
  const push = (x) => { heap.push(x); let i = heap.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (!less(heap[i], heap[p])) break; [heap[i], heap[p]] = [heap[p], heap[i]]; i = p; } };
  const pop = () => { const top = heap[0], last = heap.pop(); if (heap.length) { heap[0] = last; let i = 0; for (;;) { const l = 2 * i + 1, r = l + 1; let m = i; if (l < heap.length && less(heap[l], heap[m])) m = l; if (r < heap.length && less(heap[r], heap[m])) m = r; if (m === i) break; [heap[i], heap[m]] = [heap[m], heap[i]]; i = m; } } return top; };
  const res = [];
  let t = 0, i = 0;
  while (res.length < n) {
    if (!heap.length && t < tasks[order[i]][0]) t = tasks[order[i]][0];
    while (i < n && tasks[order[i]][0] <= t) { push([tasks[order[i]][1], order[i]]); i++; }
    const [p, j] = pop();
    t += p;
    res.push(j);
  }
  return res;
}