You have n tasks numbered 0 to n − 1. tasks[i] = [start, length] means task i becomes available at time start and takes length time units to run.
A single CPU runs one task at a time and never stops a task halfway. Whenever it is free and at least one task is available, it picks the one with the shortest length, breaking ties by the smaller index. If nothing is available, it waits. It can start a new task the moment the previous one ends.
Return the task numbers in the order the CPU runs them.
Example 1
Input: tasks = [[2, 3], [1, 4], [3, 1], [3, 2]] Output: [1, 2, 3, 0] Why: only task 1 is ready at time 1; at time 5 the shortest goes first
2 more examples and the constraints
Example 2
Input: tasks = [[4, 6], [4, 3], [4, 3], [4, 1]] Output: [3, 1, 2, 0] Why: all start at 4; tasks 1 and 2 tie on length, so 1 goes first
Example 3
Input: tasks = [[1, 2], [10, 1], [2, 5]] Output: [0, 2, 1] Why: after task 2 ends at 8 the CPU waits until task 1 starts at 10
Constraints
- 1 ≤ n ≤ 100,000
- 1 ≤ start, length ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan for the shortest ready taskO(n²)
- Sort by start, min-heap of ready tasksO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 tasks | Verdict |
|---|---|---|---|
| Scan for the shortest ready task | O(n²) | Correct, but times out | |
| Sort by start, min-heap of ready tasks | O(n log n) | Best; each task pushed and popped once |
n = the number of tasks.
Edge cases to test
- Idle gaps. [[1, 2], [10, 1], [2, 5]]: after time 8 nothing is ready, so jump to 10 instead of stepping one unit at a time.
- Ties on length. Equal lengths go by smaller index; putting the index second in the heap key handles it.
- A short task that arrives too late. [[1, 10], [2, 1], [3, 1]] gives [0, 1, 2]: once task 0 starts, it runs to the end.
- Huge times. Three tasks of length 1,000,000,000 push
timepast 2^31.
Common mistakes
- Keying the heap on length alone, so ties come out in an arbitrary order instead of by index.
- Sorting
tasksitself and losing the original indices that the answer needs. - Storing
timein a 32-bit int, which overflows on long schedules.
How to talk through it
- 1Clarify. Is a task preempted when a shorter one arrives? How are ties broken? Can the CPU sit idle?
- 2Simulate simply. Each time the CPU is free, scan all tasks for the shortest started one: O(n²).
- 3Split the two questions. Sorting by start tells me what has arrived; a heap on (length, index) tells me what to run.
- 4Handle idle time. When the heap is empty, jump
timeto the next start. - 5Test out loud. Run a tie on length, an idle gap, and a long task that blocks a short one.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?