← Uber Interview InsightsSoftware Engineer
Model the problem as finding nodes that are not part of any cycle and can only reach terminal nodes. Use a reverse graph and topological sort (Kahn's algorithm) to iteratively remove nodes with outgoing edges to non-safe nodes, or use DFS with cycle detection and memoization to mark safe nodes.
Pro tip: Clarify edge cases upfront, such as empty graph, self-loops, and multiple components. Mention that the reverse graph approach naturally handles cycles and is O(V+E), which is optimal.
Restate the definition: a safe node is one where every path from it eventually reaches a terminal node (no outgoing edges). Note that nodes in cycles or leading to cycles are unsafe.
Decide between DFS with cycle detection and memoization, or reverse graph with topological sort. Explain the trade-offs: DFS is simpler to code, reverse graph is iterative and avoids recursion depth issues.
For DFS: use three states (unvisited, visiting, safe) to detect cycles and mark safe nodes. For reverse graph: build reverse adjacency, compute out-degrees, and use a queue to process nodes with out-degree 0, marking them safe and decrementing out-degrees of predecessors.
After processing, gather all safe nodes and sort them in ascending order as required. Return the sorted list.
State time and space complexity: O(V+E) time, O(V+E) space. Walk through a small example to verify correctness, including a cycle and a terminal node.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.