Data Structures & AlgorithmsHardGoogle · Flipkart interview
A service must detect whether a dependency graph with 10⁵ modules and 10⁶ edges has a cycle. Which approach is both correct and efficient?
- A. Kahn's algorithm: a cycle exists iff some nodes never reach in-degree 0, O(V + E)
- B. Union-find: report a cycle when an edge joins two nodes already in one set
- C. BFS from every node, reporting a cycle if a node is seen twice
- D. Report a cycle whenever E ≥ V
Correct answer: A. Kahn's algorithm: a cycle exists iff some nodes never reach in-degree 0, O(V + E)
For DIRECTED graphs union-find is wrong: A→B, A→C, B→C joins the same set without a directed cycle. Kahn's algorithm (or DFS with three colours) is linear. E ≥ V implies a cycle only in undirected graphs.
More Coding Interview Problems questions
- Shortest paths in a large grid where each move costs either 0 or 1. Which algorithm is the most efficient correct choice?
- You must report the 100 largest values from a stream of 10⁹ integers using about 1 MB of memory. Which approach fits?
- Edge case: JavaScript type coercion. javascript console.log(typeof null, [] + {}, [] == ![], 0.1 + 0.2 === 0.3); What is printed?
- Edge case: += versus + on a list that has another name. python a = [1, 2, 3] b = a a += [4] a = a + [5] print(b, a) What is printed?
- Edge case: changing a dict while iterating over it. python d = {1: 'a', 2: 'b', 3: 'c'} try: for k in d: if k == 2: d[4] = 'd' print("ok"…
- Edge case: Python's round() and sorting strings with mixed case. python print(round(2.5), round(3.5), round(-0.5), sorted(['b', 'A', 'a'…