FastPrepTopological Ordering

Topological Ordering

Apple logoApple● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

There are n vertices numbered from 0 through n - 1. Each directed edge [u, v] requires u to appear before v.

Return the lexicographically smallest ordering containing every vertex exactly once and satisfying every edge. If no such ordering exists because the graph contains a directed cycle, return an empty array. With zero vertices, the result is also an empty array.

Function

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

Examples

Example 1

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

Choose the smallest currently available vertex; isolated vertex 3 still appears.

Example 2

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

The cycle prevents any ordering of all vertices.

Example 3

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

Vertex 0 must wait for vertex 2; vertex 1 is the smallest available first choice.

Constraints

  • 0 <= n <= 2000.
  • There are at most 2000 edges.
  • Every edge endpoint is in [0, n).
  • Repeated edges and self-loops are allowed.

More Apple problems

See Apple hiring insights
public int[] topologicalOrder(int n, int[][] edges) {
    // Write your code here.
}
n4
edges[[0,2],[1,2]]
expected[0,1,2,3]
Checking account…