Topological Ordering
Updated
Problem statement
There are n vertices numbered from 0 through n - 1. Each directed edge [u, v] requires u to appear before v.
Return an ordering that includes every vertex exactly once and follows every edge rule. Among valid orders, choose the lexicographically smallest: compare two orders from the start, and choose the one with the smaller vertex at the first difference. 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]At each step, place the smallest vertex whose edge rules are already met. Both edge starts go first, then the vertex both edges point to, and isolated vertex 3 comes last.
Example 2
n = 3edges = [[0,1],[1,2],[2,0]]return = []The edges form a cycle, so no order can follow every edge rule. Return an empty array.
Example 3
n = 3edges = [[2,0]]return = [1,2,0]Vertex 0 must wait for vertex 2, so vertex 1 is the smallest vertex that can go first. The waiting vertex goes last, right after the vertex it waits for.
Constraints
0 <= n <= 2000.- There are at most
2000edges. - Every edge endpoint is in
[0, n). - Repeated edges and self-loops are allowed.
More Apple Onsite Interview questions
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Merge IntervalsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- FIFO Mutex Operation TraceONSITE INTERVIEW · Seen Oct 2026
- Implement Hit CounterPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Parse Nested HTML into a TreeONSITE INTERVIEW · Seen Oct 2026
- Thread-Safe Concurrent Linked ListONSITE INTERVIEW · Seen Sep 2026
- Palindrome Match PercentageONSITE INTERVIEW · Seen Sep 2026
- Binary Tree Nodes at Distance KONSITE INTERVIEW · Seen Aug 2026
- BST to Sorted Circular Doubly Linked ListONSITE INTERVIEW · Seen Aug 2026
- Classify Natural-Month Distance Between DatesONSITE INTERVIEW · Seen Aug 2026
Similar questions at other companies
- Merge Event PreferencesAirbnb · PHONE SCREEN · ONSITE INTERVIEWAirbnb interview questions
- Network Layer Execution OrderNVIDIA · PHONE SCREENNVIDIA interview questions
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Course Schedule IIAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Shortest Travel Time in a Grid with Traffic LightsWaymo · PHONE SCREENWaymo interview questions
- Task Scheduler with Prerequisites and Execution PathsBrex · PHONE SCREEN
- Dependency-Aware Task SchedulerRippling · PHONE SCREENRippling interview questions
- Lexicographically Smallest Topological OrderByteDance · PHONE SCREEN · ONSITE INTERVIEWByteDance interview questions
- Merge Subsequences Into a Consistent Total OrderGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Shortest Paths in a Nonnegative Directed GraphNation with NaMo · PHONE SCREEN