FastPrepOrder DAG Nodes from Leaves to Roots
Problems/Order DAG Nodes from Leaves to Roots

Order DAG Nodes from Leaves to Roots

Vercel logoVercel● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report establishes the task identity and central capability. This practice contract supplies only the portable interface, deterministic boundary rules, and output serialization needed for consistent execution.

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

  • Process Banking OperationsOA · Seen Oct 2026
  • Recent Metrics by Name and TagsPHONE SCREEN · Seen Sep 2026
See Vercel hiring insights
Saved
class Solution {
    public int[] leavesToRoots(int n, int[][] edges) {
      // write your code here
    }
}
Checking account…