As reported: Google L3 virtual onsite, round 2 (2025): check whether a given graph is a ring. A BFS attempt went wrong while coding; a DFS solution satisfied the interviewer. Follow-up: for a general graph, detect a cycle.
You are given an undirected graph with n nodes, numbered 0 to n − 1, and a list of edges.
isRing(n, edges)— returntrueif the graph is a ring: allnnodes lie on one single cycle, and there is nothing else (no extra edges, no other components).- Follow-up.
hasCycle(n, edges)— for a general graph (it may be disconnected), returntrueif it contains any cycle.
Example
n = 5, edges = [[0,1],[1,2],[2,3],[3,4],[4,0]] -> ring: true, cycle: true
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]] -> ring: false, cycle: false
n = 6, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,3]] -> ring: false, cycle: true (two separate triangles)
Clarifications
- No self-loops and no duplicate edges.
- A ring needs at least 3 nodes. A single node with no edges is not a ring.
Constraints: 1 ≤ n ≤ 10^5; 0 ≤ edges.length ≤ 10^5.
Code runner format: two lines: n, then edges as a JSON array of pairs. Implement isRing(n, edges) and hasCycle(n, edges); the harness prints both results as [isRing, hasCycle].