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?

  1. A. Kahn's algorithm: a cycle exists iff some nodes never reach in-degree 0, O(V + E)
  2. B. Union-find: report a cycle when an edge joins two nodes already in one set
  3. C. BFS from every node, reporting a cycle if a node is seen twice
  4. 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

Exams that ask this topic