← Questions

Distance from every node to the cycle

0
MicrosoftCodingLast asked Jan 2026

A coding interview question asked in Microsoft's coding round, last asked Jan 2026. It tests graphs, cycles and bfs.

A connected undirected graph has n nodes and exactly n edges, so it contains exactly one cycle. For every node, return its distance (in edges) to the nearest node on the cycle; nodes on the cycle have distance 0.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • distance_to_cycle(n: int, edges: list[tuple[int, int]]) -> list[int] — nodes are 0..n-1.

Example

n = 7
edges = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 5), (1, 6)]
distance_to_cycle(n, edges)  ->  [0, 0, 0, 1, 2, 3, 1]
    # cycle 0-1-2; 3, 4, 5 hang off 2 in a chain; 6 hangs off 1

Constraints

  • 3 <= n <= 10^5; the graph is connected and has exactly one cycle, with no self-loops or duplicate edges.

Clarifying questions

  • Is the graph guaranteed connected with exactly one cycle?
  • Can the cycle have length 2 (a duplicate edge)?
  • Do I return distances only, or also which cycle node each node attaches to?

What a strong answer covers

  • Finding the cycle by peeling leaves: repeatedly remove nodes of degree 1 (a queue of leaves); the nodes left are exactly the cycle.
  • Then a multi-source BFS from all cycle nodes at distance 0 outward.
  • An alternative with DFS that finds the cycle through a back edge and parent pointers, and why leaf peeling avoids recursion depth issues.
  • O(n) time and space.
  • Tests: the whole graph is the cycle, a long tail, several trees on different cycle nodes.

Follow-ups

  • The graph is a functional graph (each node has one outgoing edge) with several cycles: distance to the nearest cycle for every node.
  • Return, for each node, the cycle node its tree hangs from.
  • The graph may be disconnected, with one cycle per component.

Where it's asked

  • Microsoft · Coding · Last asked Jan 202660 min · Ten to fifteen minutes of behavioral questions, then coding in HackerRank where you write a main and make the tests pass; usually three rounds · No AI unless the interviewer invites it; some 2026 loops add a round where you bring your own AI agent

What it tests

graphs · cycles · bfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding