Single-Threaded CPU

Medium · Heap & Counting · Array · Sorting · Heap (Priority Queue)

Problem

You are given n tasks labelled 0 to n - 1 as a list tasks, where tasks[i] = [enqueueTime, processingTime]: task i becomes available at enqueueTime and takes processingTime units to run.

A single-threaded CPU processes them like this:

Return the order in which the CPU processes the tasks.

Examples

Input: tasks = [[1,5],[2,3],[3,1],[4,1]]
Output: [0,2,3,1]

Task 0 runs from 1 to 6; by then tasks 1 to 3 are waiting, and the two 1-unit tasks go first, by index.

Input: tasks = [[5,2],[5,2],[5,1]]
Output: [2,0,1]

All arrive at 5: task 2 is shortest, then tasks 0 and 1 tie and go by index.

Input: tasks = [[1,2],[8,4],[2,3]]
Output: [0,2,1]

Task 0 runs 1 to 3, task 2 runs 3 to 6, then the CPU idles until task 1 arrives at 8.

Constraints

Approaches

Follow-up

The same simulation answers other questions about the schedule, such as how long tasks wait in total, and extends to several processors with a second heap of finishing times. See the use cases.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…