progress

~/problems / Graphs / Cycle detection

Spreadsheet: show the circular reference

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A spreadsheet app refuses to recalculate when formulas refer to each other in a loop, and its error message should show the loop, e.g. B2 -> C7 -> B2.

Write find_loop(formulas) -> list[str]:

  • formulas maps a cell to the cells its formula reads: {"A1": ["B1", "C1"]}. A cell that isn't a key (or maps to []) reads nothing. References may repeat.
  • If there is a loop, return it as distinct cells [c1, ..., ck] where each reads the next and ck reads c1. Any loop, from any starting cell, is fine; a cell reading itself is [c].
  • With no loop, return [].
find_loop({"A1": ["B1"], "B1": ["C1", "D1"], "C1": ["A1"]})
# ["A1", "B1", "C1"]   (or ["B1", "C1", "A1"], or ["C1", "A1", "B1"])
find_loop({"A1": ["B1", "C1"], "B1": ["D1"], "C1": ["D1"]})
# []   two formulas reading D1 is not a loop
find_loop({"X9": ["X9"]})
# ["X9"]

Up to 500 cells with formulas and 10,000 references, so plain recursion is fine.

⭐ Bonus: a speed test with many ways to reach the same cells earns a star if you never re-explore a cell you've fully checked (that takes exponential time).

Show hint

use a three-colour DFS, as in Basics: does a directed graph have a cycle?: white = not visited yet, grey = on the current path, black = fully checked. Keep the current path as a list. Stepping onto a grey cell, the loop is the path from that cell to the end.

Topic: Cycle detection. Visited / on-stack sets; symlinks, CNAMEs, instruction loops.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc