Practice problem · easy
You work on the packing station of a parcel-delivery app. Packing a parcel is a list of tasks with names, such as box, pad and seal. Some tasks must be done before others: the box is built before it is padded.
The station screen shows one task at a time. When several tasks are ready, the screen shows the one whose name comes first in the alphabet, so every worker sees the same list. If the rules loop, no list exists.
Write task_order(tasks, firsts, thens).
tasks is a list of distinct task names, in any order.firsts[i] and thens[i] are task names: firsts[i] must be done before thens[i] can start.[] when no order exists.Input: tasks = ["seal", "box", "pad", "label", "weigh"], firsts = ["box", "box", "pad", "seal"], thens = ["pad", "weigh", "seal", "label"]
Output: ["box", "pad", "seal", "label", "weigh"]Pad and weigh both need box. Seal needs pad, and label needs seal. Kahn's algorithm keeps the ready tasks in a heap ordered by name.
| Round | Ready (heap) | Take | Order so far |
|---|---|---|---|
| 1 | box | box | box |
| 2 | pad, weigh | pad | box, pad |
| 3 | seal, weigh | seal | box, pad, seal |
| 4 | label, weigh | label | box, pad, seal, label |
| 5 | weigh | weigh | all five |
Weigh was ready from round 2, but its name comes after the others, so it goes last.
Input: tasks = ["fold", "tape"], firsts = ["fold", "tape"], thens = ["tape", "fold"]
Output: []Fold must come before tape, and tape before fold. Neither can start, so no order exists.
Input: tasks = ["tape", "box", "pad"], firsts = [], thens = []
Output: ["box", "pad", "tape"]No rules. Every task is ready, and the screen shows them alphabetically.
1 ≤ len(tasks) ≤ 100,000, and every name is 1 to 10 lowercase letters, all differentlen(firsts) = len(thens), at most 100,000, and every name in them is in tasksThere can be 100,000 tasks and 100,000 rules. Scanning all the names every time one is chosen would be about 20 billion steps. A heap of ready names touches each task and each rule only a few times, in (n + m) log n: a few million steps.
task_order · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.