educative.io

Problem with topological sort algorithm given as solution

I don’t believe the solution is robust. For instance, it seems to fail if a node towards the top (an early ancestor) has a child that has no children. That child gets put to the front of the list. In the following graph, the solution code puts 13 in the first position, whereas 11 or 10 should be first.

g3 = Graph(14)

g3.addEdge(11,12)
g3.addEdge(11,9)
g3.addEdge(10,9)
g3.addEdge(12,13)
g3.addEdge(12,14)
g3.addEdge(12,8)
g3.addEdge(9,8)
g3.addEdge(14,1)
g3.addEdge(8,7)
g3.addEdge(8,6)
g3.addEdge(8,5)
g3.addEdge(5,1)
g3.addEdge(5,2)
g3.addEdge(5,3)

print(topologicalSort(g3))
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]


Course: Recursion for Coding Interviews in Python - Learn Interactively
Lesson: Solution Review 3: Topological Sorting of a Graph - Recursion for Coding Interviews in Python