Topological sort · Medium
Some form fields are computed from earlier fields. A validation engine needs a deterministic evaluation order or a clear cycle signal.
Return the lexicographically smallest topological ordering of field IDs or null when a cycle exists.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ fields: string[], dependencies: [before:string, after:string][] }
Input rules
- Fields are unique; endpoints exist; duplicate edges are allowed.
What each field means
fields— all unique field IDs that must appear in the result.- Each
[before, after]independenciesrequiresbeforeto appear earlier thanafter.
Output
Return value and rules
- Return every field exactly once in a valid dependency order.
- Whenever several fields are ready, choose the smallest ID in ASCII order.
- Return
nullif a cycle makes an order impossible; return[]for no fields.
Constraints
- 0 <= fields.length <= 2000; 0 <= dependencies.length <= 20000
- IDs contain lowercase ASCII letters and digits. A self-edge is a cycle.
Examples
Example 1
{
"dependencies": [
[
"a",
"c"
],
[
"b",
"c"
]
],
"fields": [
"c",
"a",
"b"
]
}Returns
[
"a",
"b",
"c"
]Example 2
{
"dependencies": [],
"fields": []
}Returns
[]Required complexity
O(n² + m) time and O(n + m) space