# Why does this topological sort report a cycle for a valid dependency graph?

**URL:** <https://forum.kirupa.com/t/why-does-this-topological-sort-report-a-cycle-for-a-valid-dependency-graph/679945>\
**Category:** web dev\
**Created:** [April 3, 2026, 7:00pm UTC](https://forum.kirupa.com/t/why-does-this-topological-sort-report-a-cycle-for-a-valid-dependency-graph/679945 "2026-04-03T19:00:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Quelly](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/quelly/32/31386_2.png) [@Quelly](https://forum.kirupa.com/u/Quelly)\
**Post date:** [April 3, 2026, 7:00pm UTC](https://forum.kirupa.com/t/why-does-this-topological-sort-report-a-cycle-for-a-valid-dependency-graph/679945/1 "2026-04-03T19:00:12Z")

</div>

I’m implementing Kahn’s algorithm, but some acyclic inputs return an empty result because `indegree` seems wrong after setup. I expect `["build","test","deploy"]` for the example below. What am I counting incorrectly?

```js
function topo(edges) {
  const indegree = new Map(), graph = new Map();
  for (const [a, b] of edges) {
    graph.set(a, (graph.get(a) || []).concat(b));
    indegree.set(a, (indegree.get(a) || 0) + 1);
    if (!indegree.has(b)) indegree.set(b, 0);
  }
  const q = [...[...indegree].filter(([, d]) => d === 0).map(([n]) => n)];
  return q;
}

```

Quelly

---

<div class="post-metadata">

**Author:** ![Ellen1979](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/ellen1979/32/31260_2.png) [@Ellen1979](https://forum.kirupa.com/u/Ellen1979)\
**Post date:** [April 3, 2026, 7:14pm UTC](https://forum.kirupa.com/t/why-does-this-topological-sort-report-a-cycle-for-a-valid-dependency-graph/679945/2 "2026-04-03T19:14:06Z")

</div>

You’re incrementing the source node instead of the destination, so for `build -> test` you should add to `indegree["test"]`, not `indegree["build"]`, and also make sure every node exists in `graph` so sinks don’t disappear later.

Ellen
