FastPrepTopological Sort for Ads Tasks

Topological Sort for Ads Tasks

Netflix logoNetflix● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given numTasks tasks labeled from 0 to numTasks - 1 and a list of prerequisite edges. Each edge [before, after] means task before must be completed before task after.

Return one valid order to complete all tasks. If more than one task is available at the same time, choose the smaller task id first so the result is deterministic. If it is impossible to complete all tasks because the dependency graph contains a cycle, return an empty array.

Function

findTaskOrder(numTasks: int, edges: int[][]) → int[]

Examples

Example 1

numTasks = 4edges = [[0, 1], [0, 2], [1, 3], [2, 3]]return = [0, 1, 2, 3]

Task 0 unlocks tasks 1 and 2. The smaller available id is chosen first.

Example 2

numTasks = 2edges = [[0, 1], [1, 0]]return = []

The two tasks depend on each other, so no valid topological order exists.

Constraints

  • 0 <= before, after < numTasks
  • Use topological sorting with cycle detection.
  • When multiple tasks have in-degree zero, choose the smallest task id first.

More Netflix problems

See Netflix hiring insights
public int[] findTaskOrder(int numTasks, int[][] edges) {
  // write your code here
}
numTasks4
edges[[0, 1], [0, 2], [1, 3], [2, 3]]
expected[0, 1, 2, 3]
Checking account…