Data Structures and Algorithms
Tasks A to E have the ordering constraints “A before C”, “B before C”, “C before D”, “B before E” and “E before D”. Which order satisfies all the constraints (a result of topological sorting)?
- AA, C, B, E, D
- BB, A, E, C, D
- CB, E, D, A, C
Show answer and explanation
Answer: B. B, A, E, C, D
In B, A, E, C, D, A and B come before C, C and E come before D, and B comes before E, so all five constraints are met. A, C, B, E, D does C before B, violating “B before C”, and B, E, D, A, C does D before C, violating “C before D”. Topological sorting arranges the vertices of a directed acyclic graph (DAG) so that every edge points from earlier to later; it can be done by repeatedly taking a vertex with no incoming edges (Kahn's algorithm) or with depth-first search. The answer is not always unique: this example has five valid orders.
- A. It does C before B, violating “B before C”.
- B. Correct. It satisfies all five constraints.
- C. It does D before C, violating “C before D”.