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 FalseWhy does it report a cycle on the simple path 0 – 1 – 2?- A. It should use BFS – DFS cannot detect cycles
- B. seen must be cleared after each call
- C. It treats the edge back to the parent as a cycle; it must pass the parent and skip v == parent
- 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
- Problem: Climbing-stairs memoisation in Python: python def ways(n, memo={}): if n <= 1: return 1 if n in memo: return memo[n] memo[n] =…
- Problem: Reverse a singly linked list (C++): cpp Node prev = nullptr; while (head) { head->next = prev; // line 3 prev = head; head =…
- Problem: A sliding-window solution for 'longest substring with at most k distinct characters' keeps a frequency map and shrinks while…
- Problem: Merge sort's merge step in Java uses if (a[i] < b[j]) take a[i]; else take b[j];. What property is lost compared with <=?
- Problem: The 'two-sum on a sorted array' code below has a subtle edge-case behaviour. What does it print? python def twosumsorted(a, t)…
- Problem: A ride app must repeatedly add drivers with ratings and remove the highest-rated driver, n = 10⁵ operations. Which data structure…