Amazon VO Interview Question: Determine if an Undirected Graph Has a Cycle

17 Views
No Comments

Determine if an undirected graph has cycle.

Example 1:

[[1,2],[1,3],[2,3]] -> return true

Example 2:

[[1,2],[2,3],[3,4],[1,5]] -> return false

This problem asks whether an undirected graph contains a cycle. A standard solution is to build an adjacency list and run DFS while tracking the parent node, or use Union-Find to detect when an edge connects two vertices that are already in the same set. In the first example, [[1,2],[1,3],[2,3]] forms a triangle, so the answer is true. In the second example, [[1,2],[2,3],[3,4],[1,5]] has no cycle, so the answer is false.

END
 0