Distance to a Cycle in Undirected Graph - Problem

You are given a positive integer n representing the number of nodes in a connected undirected graph containing exactly one cycle. The nodes are numbered from 0 to n - 1 (inclusive).

You are also given a 2D integer array edges, where edges[i] = [node1i, node2i] denotes that there is a bidirectional edge connecting node1i and node2i in the graph.

The distance between two nodes a and b is defined to be the minimum number of edges that are needed to go from a to b.

Return an integer array answer of size n, where answer[i] is the minimum distance between the ith node and any node in the cycle.

Input & Output

Example 1 — Basic Cycle with Branches
$ Input: n = 7, edges = [[1,2],[2,4],[4,3],[3,1],[0,1],[5,4],[6,5]]
Output: [1,0,0,0,0,1,2]
💡 Note: The cycle is nodes 1→2→4→3→1. Node 0 is distance 1 from cycle node 1. Node 5 is distance 1 from cycle node 4. Node 6 is distance 2 from cycle (via node 5 to node 4).
Example 2 — Simple Triangle
$ Input: n = 3, edges = [[0,1],[1,2],[2,0]]
Output: [0,0,0]
💡 Note: All nodes 0, 1, 2 form the cycle, so distance to cycle is 0 for all nodes.
Example 3 — Cycle with Long Chain
$ Input: n = 6, edges = [[0,1],[1,2],[2,0],[3,1],[4,3],[5,4]]
Output: [0,0,0,1,2,3]
💡 Note: Cycle is 0→1→2→0. Node 3 connects to cycle node 1 (distance 1). Node 4 connects via node 3 (distance 2). Node 5 connects via nodes 4→3→1 (distance 3).

Constraints

  • 3 ≤ n ≤ 105
  • n - 1 ≤ edges.length ≤ 105
  • edges[i].length == 2
  • 0 ≤ node1i, node2i ≤ n - 1
  • node1i != node2i
  • The graph is connected.
  • The graph has exactly one simple cycle.

Visualization

Tap to expand
Distance to a Cycle in Undirected Graph INPUT 1 2 4 3 0 5 6 n = 7 edges = [[1,2],[2,4], [4,3],[3,1],[0,1], ALGORITHM (DFS) 1 Find Cycle DFS to detect nodes forming the cycle 2 Mark Cycle Nodes Nodes 1,2,3,4 are in cycle (dist=0) 3 BFS from Cycle Calculate distance for non-cycle nodes 4 Compute Distances 0-->1: dist=1 5-->4: dist=1 6-->5-->4: dist=2 Distance Table Node: 0 1 2 3 4 5 6 Dist: 1 0 0 0 0 1 2 Cycle: - OK OK OK OK - - FINAL RESULT 1:0 2:0 4:0 3:0 0:1 5:1 6:2 Cycle (dist=0) Non-cycle nodes Output: [1,0,0,0,0,1,2] Key Insight: 1. Use DFS to detect the unique cycle in the graph by tracking visited nodes and finding back edges. 2. Once cycle nodes are identified (distance=0), perform BFS from all cycle nodes simultaneously to compute minimum distances for remaining nodes. Time Complexity: O(n) TutorialsPoint - Distance to a Cycle in Undirected Graph | DFS Approach
Asked in
Google 12 Facebook 8 Amazon 6 Microsoft 4
15.7K Views
Medium Frequency
~25 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen