FastPrepOrder DAG Nodes from Leaves to Roots

Order DAG Nodes from Leaves to Roots

Vercel logoVercel● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

You are given a directed graph whose edges point from parent nodes to child nodes. Repeatedly take every current leaf (a node with outdegree zero), emit that layer in ascending node order, and remove those nodes and their incoming edges.

Return the concatenation of the leaf layers. Return an empty array if a directed cycle prevents all nodes from being removed.

Function

leavesToRoots(n: int, edges: int[][]) → int[]

Examples

Example 1

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

Leaves 1 and 3 form the first sorted layer, followed by 2 and then 0.

Example 2

n = 3edges = [[0,1],[1,2],[2,0]]return = []

The cycle has no removable leaf.

Constraints

  • 1 <= n <= 100000.
  • Every edge has two valid node IDs and appears once.

More Vercel problems

See Vercel hiring insights
public int[] leavesToRoots(int n, int[][] edges) {
  // write your code here
}
n4
edges[[0,1],[0,2],[2,3]]
expected[1,3,2,0]
Checking account…