149Build a graph-based workflow editor with cycle detection and execution ordering
hardAbout 75 minutesCodinggraphsdagtopological-sortasync
Problem
Tools like Zapier, n8n and GitHub Actions let users connect steps into a directed acyclic graph (DAG): "when a form is submitted → enrich the lead → (send email, add to CRM) → notify Slack". Implement the model behind such an editor:
createWorkflow() returns:
addNode(id, run):run(inputs)is async;inputsmaps each predecessor id to its output. Duplicate ids throw.addEdge(from, to): throws for unknown nodes or self-loops, ignores duplicates, and throwsError("Edge a -> b would create a cycle: b -> c -> a")(the path fromtoback tofrom) instead of adding an edge that creates a cycle.wouldCreateCycle(from, to): the same check without changing anything (the UI uses it to show a red line while dragging).removeEdge(from, to),removeNode(id)(also removes its edges).order(): a topological order; among nodes that are ready at the same time, keep the order in which they were added.levels(): groups of nodes that can run in parallel (level 0 has no predecessors, level n depends only on earlier levels).run(): execute the workflow. Each node starts as soon as all its predecessors succeeded; independent nodes run concurrently. If a node fails, record its error and skip everything downstream of it, but keep running independent branches. Resolve{ results, errors, skipped }(resultsanderrorskeyed by id,skippeda sorted list).
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Step-by-step
Store nodes in a Map (insertion order matters for determinism), plus outgoing and incoming sets per node. Most operations need one direction or the other.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.