Javascript | Topological Sort w/ Comments
\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[][]}\n */\nvar getAncestors = function(n, edges) {\n    // create in-degree tracke
```\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[][]}\n */\nvar getAncestors = function(n, edges) {\n    // create in-degree tracker (array)\n    const inDegrees = Array(n).fill(0);\n    \n    // maintain the results in a hash for each node\n    const res = {}\n    for (let i = 0; i < n; i++) {\n        res[i] = new Set();\n    }\n    \n    // create the graph + increment in-degrees\n    const graph = {};\n    for (const [from, to] of edges) {\n        inDegrees[to]++;\n        \n        if (!graph[from]) {\n            graph[from] = [];\n        }\n        graph[from].push(to);\n    }\n    \n    // build queue for top sort where in-degree === 0\n    const q = [];\n    for (let i = 0; i < n; i++) {\n        if (inDegrees[i] === 0) {\n            q.push(i);\n        }\n    }\n    \n    // perform top sort w/ motifications\n    while (q.length) {\n        const node = q.shift();\n        const neighbors = graph[node] || [];\n\n        for (const neighbor of neighbors) {\n            // add this node to its child\'s ancestor set\n            res[neighbor].add(node);\n            // add each of this node\'s ancestors to its child\'s ancestor set\n            for (const v of res[node]) {\n                res[neighbor].add(v)\n            }\n            \n            // decrease the in-degree for this node\'s child + check if should be added to top sort\n            inDegrees[neighbor]--\n            if (inDegrees[neighbor] === 0) {\n                q.push(neighbor);\n            }\n        }\n    }\n    \n    // turn the sets into arrays + sort them\n    const result = [];\n    for (const set of Object.values(res)) {\n        const arr = Array.from(set);\n        arr.sort((a,b) => a-b);\n        result.push(arr)\n    }\n    return result\n};\n\n```
['Depth-First Search', 'Topological Sort', 'JavaScript']