SDE & MLE Prep

1834. Single-Threaded CPU

Problem

tasks[i] = [enqueueTime, processingTime]. A single-threaded CPU, whenever idle, starts the available task with the shortest processing time (ties: smallest index) and runs it to completion; if nothing is available it waits. Return the order in which the tasks are processed.

Example: [[1,2],[2,4],[3,2],[4,1]] → [0,2,3,1]

Constraints: up to 10⁵ tasks.

Sort tasks by enqueue time. At each step, push all tasks that have arrived by time into a heap keyed by (processing time, index); run the top. If the heap is empty, jump time to the next arrival.

Complexity: O(n log n).

class Solution:
    def getOrder(self, tasks: List[List[int]]) -> List[int]:
        order = sorted(range(len(tasks)), key=lambda i: tasks[i][0])
        h, res, time, i = [], [], 0, 0
        while len(res) < len(tasks):
            if not h and time < tasks[order[i]][0]:
                time = tasks[order[i]][0]
            while i < len(order) and tasks[order[i]][0] <= time:
                j = order[i]
                heappush(h, (tasks[j][1], j))
                i += 1
            p, j = heappop(h)
            time += p
            res.append(j)
        return res