Skip to content

Conversation

@CodeWithBehnam
Copy link
Owner

Summary

Optimise the graph traversal algorithm in the execution engine from O(n²) to O(n+e) complexity.

Problem

The original Kahn's algorithm implementation had a nested loop that scanned all nodes to find dependents:

```typescript
// O(n) for each node processed = O(n²) total
for (const otherNode of nodes) {
if (dependencies.get(otherNode.id)?.has(node.id)) {
// ...
}
}
```

Solution

Build a reverse adjacency list (dependents map) during the initial graph scan, enabling O(1) lookup:

```typescript
// O(1) lookup of nodes that depend on this one
const nodeDependents = dependents.get(node.id)
for (const dependentId of nodeDependents) {
// ...
}
```

Complexity Analysis

  • Before: O(n²) where n = number of nodes
  • After: O(n + e) where n = nodes, e = edges
  • For a graph with 100 nodes and 200 edges: ~10,000 → ~300 operations

Changes

  • Add dependents map (reverse adjacency list)
  • Add nodeById map for O(1) node lookup by ID
  • Eliminate nested loop in Kahn's algorithm main loop

Behnam Ebrahimi

- Add reverse adjacency list (dependents map) for O(1) dependent lookup
- Add nodeById map for O(1) node access by ID
- Eliminate nested loop that scanned all nodes for each processed node
- Complexity now O(n + e) where n = nodes, e = edges

Co-Authored-By: Behnam & Claude Code
@CodeWithBehnam CodeWithBehnam merged commit d9b0422 into main Dec 25, 2025
2 checks passed
@CodeWithBehnam CodeWithBehnam deleted the perf/graph-traversal-optimisation branch December 25, 2025 16:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants