educative.io

Educative

Topological Sort, JS

The JS code for topological sort does not work if the input is the following
vertices = 3, edges = [[1,2],[2,3],[3,1]]

It throws a TypeError on line 18
/usercode/index.js:20
graph[parent].push(child); // put the child into it’s parent’s list
^

TypeError: Cannot read property 'push' of undefined
    at /usercode/index.js:18:19

Please look into this and fix this ASAP


Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/6010387461832704

Hi @Varun_Chillara!
It throws an exception because the edges you provide form a directed cycle, and topological sort work if and only if there is no directed cycle in the graph.