Data Structures & AlgorithmsVery hardAmazon · Microsoft coding round
Problem: Topological sort is only defined for which kind of graph, and what happens if Kahn's algorithm is run on a graph that violates this?
- A. Only a Directed Acyclic Graph (DAG); if a cycle exists, some nodes never reach in-degree 0 and are left out of the output, signalling the cycle
- B. Only undirected graphs
- C. Any directed graph, cycles included, always producing a valid full order
- D. Only trees, never general DAGs
Correct answer: A. Only a Directed Acyclic Graph (DAG); if a cycle exists, some nodes never reach in-degree 0 and are left out of the output, signalling the cycle
A topological order requires no cycles (a DAG); Kahn's algorithm detects a cycle indirectly because any node inside the cycle never has all its incoming edges 'removed', so it never enters the queue, and the final output omits it.
More Coding Interview Problems questions
- Problem: Which best explains why merge sort is preferred over quicksort for sorting linked lists (as opposed to arrays)?
- Problem: Which best explains the time complexity difference between recursive (top-down with memoization) and iterative (bottom-up…
- Problem: What is the time complexity of building a trie from n words with total character count L, and what is the space complexity?
- Problem: A problem is solved via binary search on the answer (not on an array index) -- e.g. 'minimum capacity to ship packages within D…
- Problem: Which of these is the correct worst-case time complexity of building a max-heap from an array of n unsorted elements using the…
- Problem: In a graph represented with an adjacency list, what is the space complexity, and how does it compare to an adjacency matrix for a…