Ctrl K

Task Plan by Teams

Hard
There are n tasks numbered 0 to n - 1 and m teams numbered 0 to m - 1. Task i belongs to team team[i], or to no team at all if team[i] = -1. A team may have no tasks. after[i] lists the tasks that must appear in the plan before task i (not necessarily right before it). Build a plan, an order of all n tasks, such that: - for every task, all tasks in after[i] come earlier; - the tasks of each team appear consecutively, with no other tasks in between. Return the plan, or an empty list if no such plan exists. The input guarantees that whenever a plan exists, it is unique.
Example 1
n=4, m=1, team=[0, -1, 0, -1], after=[[3], [2], [0], []] → [3, 0, 2, 1]

Task 3 unlocks task 0, which is followed by task 2 from the same team, and only then task 1. Team 0 (tasks 0 and 2) stays together.

Example 2
n=3, m=1, team=[0, -1, 0], after=[[], [0], [1]] → []

Task 1 waits for task 0 and task 2 waits for task 1, so task 1 would have to sit between the two tasks of team 0 and split it. No valid plan exists, so the answer is empty.

Example 3
n=3, m=2, team=[1, 1, 0], after=[[2], [0], []] → [2, 0, 1]
Constraints
  • 1 ≤ m ≤ n ≤ 3 · 10⁴
  • len(team) = len(after) = n
  • -1 ≤ team[i] ≤ m - 1
  • 0 ≤ after[i][j] ≤ n - 1, after[i][j] ≠ i
  • The numbers within each after[i] are distinct
  • There is either no valid plan or exactly one
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLetter Order From a Dictionary HardLongest Uphill Walk HardUphill-Only Walks HardLongest Loop of Hops HardSpread the News to Everyone Hard
loading Python…
Input
n=4, m=1, team=[0, -1, 0, -1], after=[[3], [2], [0], []]
Expected
[3, 0, 2, 1]

Run checks the first 3 tests in your browser. Submit checks all 30 tests on the server, hidden ones included.