Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Detect whether an undirected graph has a cycle with DFS:

Problem: Detect whether an undirected graph has a cycle with DFS:
def dfs(u):
    seen.add(u)
    for v in adj[u]:
        if v in seen: return True     # line 4
        if dfs(v): return True
    return False
Why does it report a cycle on the simple path 0 – 1 – 2?
  1. A. It should use BFS – DFS cannot detect cycles
  2. B. seen must be cleared after each call
  3. C. It treats the edge back to the parent as a cycle; it must pass the parent and skip v == parent
  4. D. Line 4 should return False

Correct answer: C. It treats the edge back to the parent as a cycle; it must pass the parent and skip v == parent

In an undirected graph each edge appears in both adjacency lists, so from 1 the DFS immediately sees 0 (already seen) and wrongly reports a cycle. Track the parent: a seen neighbour other than the parent closes a real cycle. Union-find is an alternative.

More Coding Interview Problems questions

Exams that ask this topic