Python coding

Task order on a single core

A processor with one core gets tasks, where tasks[i] = [arrive, length]: task i can start at time arrive or later and runs for length time units without pausing. Whenever the core is free and at least one task has arrived and is waiting, it starts the waiting task with the shortest length, breaking ties by the smaller index i. If none is waiting, the core sits idle until the next arrival. A task that arrives just as another ends counts as waiting. Return the indexes in the order the core runs them.

There is at least one task, arrive ≥ 0 and length ≥ 1; tasks is not sorted. Aim for O(n log n).

Besides the tests, one large input (3,000 tasks) with a ~220 ms limit (scaled to your device's speed): brute force won't pass.

  • task_order([[0,4],[1,2],[2,1],[3,3]]) → [0,2,1,3]
  • task_order([[5,2],[5,2],[5,1]]) → [2,0,1]
  • task_order([[0,1],[10,3],[4,2]]) → [0,2,1]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Two orders are at play: tasks become available by arrival time, and the core picks by length. Sort the indexes by arrival once; keep the waiting tasks in a min-heap.

Hint 2

Each time the core is free, push every task that has arrived by now as (length, index), which also settles ties, then pop one and add its length to now.

Hint 3

When the heap is empty, jump now straight to the next arrival instead of ticking one unit at a time: times can be huge.

Solution and why it works
pythonO(n log n) · O(n)
import heapq


def task_order(tasks: list[list[int]]) -> list[int]:
    arrivals = sorted(range(len(tasks)), key=lambda i: tasks[i][0])
    waiting, order = [], []              # min-heap of (length, index): ties go to the lower index
    now = nxt = 0
    while len(order) < len(tasks):
        if not waiting:                  # idle: jump to the next arrival
            now = max(now, tasks[arrivals[nxt]][0])
        while nxt < len(tasks) and tasks[arrivals[nxt]][0] <= now:
            i = arrivals[nxt]
            heapq.heappush(waiting, (tasks[i][1], i))
            nxt += 1
        length, i = heapq.heappop(waiting)
        now += length                    # runs to the end, no interruptions
        order.append(i)
    return order

The core keeps needing the shortest waiting task while new ones arrive: a min-heap of (length, index) serves that, and the index settles ties. Sorting by arrival once lets a pointer feed the heap with every task that has arrived by now. Each task is pushed and popped once: O(n log n). Two traps: rescanning every task at each step is O(n²), and an idle core must jump to the next arrival, not start a task before it arrives.