AI Interviews · Question

Traverse spreadsheet cell dependencies and detect cycles.

Coding (DSA) question reported at Sierra (Dec 2025). Sources, confidence and an answer card.

Researched · updated

eng-115 AI Engineer Classic DSA & object-oriented design Coding (DSA) Medium confidence
On this page

What they’re really asking

If you only remember one thing, say this in the first minute: “Cells and their references form a graph, and a circular reference is a cycle in it. I’ll find it with a depth-first search that marks each cell white (not seen), grey (on the path I’m walking now) or black (finished). Reaching a grey cell means I’ve come back to my own path, so that’s a cycle, and I return the path so the user knows which cells to fix. I’ll use an explicit stack instead of recursion, so a long chain of cells can’t hit Python’s recursion limit.”

The rest of this page explains each part of that answer.

This is graph traversal with cycle detection, dressed as a spreadsheet. Each cell is a node. If B1’s formula reads A1, there is an edge from B1 to A1. A circular reference (A1 reads B1, B1 reads A1) is a cycle: a path of edges that comes back to where it started. No value can ever be computed for a cell on a cycle.

What makes it more than a textbook exercise is the detail you must get exactly right. The obvious “visited” set gives wrong answers on a common shape, recursion breaks on long sheets, and “true” is a poor answer when a user needs to know which cells to fix. The interviewer is watching for those three things.

The Sierra question list on Aced (a site that aggregates reported questions) words it as traversing “cell dependencies in an Excel-like spreadsheet” and detecting “circular references between cells”, posted about ten months before 2026-10-11 (Aced (formerly Exponent)aggregator). It is an aggregator entry, so the round and the follow-ups aren’t known. Expect it to grow into evaluation and recompute, as the Harvey “design spreadsheet” reports describe (Acedfirst-hand).

Clarify first

  • Input: a map from cell to formula string, or to a parsed list of references? Assume strings; you parse references with a regular expression like [A-Z]+[0-9]+.
  • Output: a yes/no, the first cycle found, or every cell on a cycle? Assume you return one cycle as a path, which is more useful to a user than “true”.
  • Size: thousands of cells? Then Python’s recursion depth matters; use an explicit stack.
  • Traversal order asked for: all cells a given cell depends on, or an order to evaluate the whole sheet in?

Say it like this: “I’ll return one cycle as a list of cells, because the user has to fix specific cells. And I’ll use an explicit stack, since a sheet can have a chain of thousands of cells.”

Answer

Words you need first

  • Depth-first search (DFS) follows one path as far as it goes before backing up. You know it from walking a directory tree.
  • Three-state (three-colour) DFS marks each node white (not visited yet), grey (on the path being walked right now) or black (fully explored, no cycle through it). Only grey means “I’m inside this one right now”.
  • A diamond is two different paths to the same cell. D1 reads B1 and C1, and both read A1. That is not a cycle, but it visits A1 twice.

Why two colours are not enough

With a plain visited set, the search visits A1 through B1, marks it visited, then reaches A1 again through C1 and wrongly reports a cycle. The grey/black split fixes this. When the search comes back to A1 through C1, A1 is already black (finished), so it is skipped. Only a grey cell, one still on the current path, closes a loop.

The code

An explicit stack replaces recursion. Each stack entry is a cell plus an iterator over its references, so the search can resume where it left off after backing up. path mirrors the grey cells in order, which is what makes returning the cycle cheap.

def find_cycle(graph):
    """Iterative three-colour DFS. Returns one cycle as a list of nodes, or None."""
    WHITE, GREY, BLACK = 0, 1, 2
    colour = defaultdict(int)
    for root in list(graph):
        if colour[root]:
            continue
        stack, path = [(root, iter(graph.get(root, ())))], [root]
        colour[root] = GREY
        while stack:
            node, it = stack[-1]
            nxt = next(it, None)
            if nxt is None:
                colour[node] = BLACK
                stack.pop()
                path.pop()
            elif colour[nxt] == GREY:
                return path[path.index(nxt):] + [nxt]
            elif colour[nxt] == WHITE:
                colour[nxt] = GREY
                stack.append((nxt, iter(graph.get(nxt, ()))))
                path.append(nxt)
    return None

Build graph as cell to the cells it references.

One sheet through it

Take the diamond: D1 = =B1+C1, B1 = =A1, C1 = =A1, and A1 empty. Run the function, then change A1 to =D1 and run it again. (These results come from running the code above.)

StepPath (grey cells)What happensWhat to say in the interview
1D1 → B1 → A1A1 has no references; it turns black”Finished cells are black; they can never be part of a new cycle.”
2D1 → C1C1 reaches A1, which is black: skip”This is the diamond. A plain visited set would call it a cycle.”
3(empty)all black; returns None”No cycle.”
4A1 = =D1; path D1 → B1 → A1A1 reaches D1, which is grey”D1 is on my current path, so I’ve looped.”
5returns ['D1', 'B1', 'A1', 'D1']”That list is what the error message shows the user.”
  • All dependencies of one cell: the same DFS from that cell, collecting the cells that turn black.
  • Evaluation order: the order in which cells turn black is a valid order to compute them in (everything a cell reads finishes before it does). Kahn’s algorithm gives the same result another way: count each cell’s unfinished inputs and repeatedly take cells whose count is zero. It also reports leftovers: cells whose count never reaches zero are on a cycle or depend on one.
  • Evaluate: compute each cell once, in that order, caching results (memoization).

Tests: a self-reference (A1 = A1), a two-cell cycle, a long chain with no cycle, a diamond (which catches the two-colour bug), and a cell that references an empty cell. The DFS above passed a 500-case random test against Kahn’s algorithm when run on 2026-10-12.

Say it like this: “I tested it against Kahn’s algorithm on random graphs, because two different methods agreeing is stronger evidence than my hand-written cases.”

Senior vs Staff

Cell dependencies

Senior

  • Three-state DFS with an explicit stack, returns the cycle path, tests the diamond case.

Staff

  • Asks whether this check runs on every edit; if so, checks only whether the edited cell's new references can reach it (cost proportional to the affected region, not the sheet), and explains what the user should see.

Small-team version

The same check guards any configuration a team lets people edit as a graph: workflow steps, prompt templates that include other templates, feature flags that depend on other flags. A cycle there doesn’t fail loudly; it hangs a job or recurses until something runs out of memory.

  • Validate at write time, when someone saves the config, not when a job runs at 2 a.m.
  • Show the cycle path in the error message. “Template support includes tone, which includes support” is fixable in a minute; “cycle detected” is not.
  • Buy for job graphs. Your workflow engine already rejects cycles; write this yourself only for your own config formats. It is a few dozen lines and saves an outage.

Pitfalls

  • A single visited set (two colours). It flags diamonds as cycles.
  • Recursion on a long chain. Python’s default limit is about a thousand frames, so a long column of formulas crashes.
  • Returning only “true”. The user needs to know which cells to fix.
  • Parsing references with string splits. They miss multi-letter columns like AA10.

Go deeper

Family