Practice
from collections import deque
def eventualSafeNodes(graph):
n = len(graph)
reverse_graph = [[] for _ in range(n)]
in_degree = [0] * n
for u in range(n):
for v in graph[u]:
reverse_graph[v].append(u)
in_degree[u] = len(graph[u])
queue = deque([i for i in range(n) if in_degree[i] == 0])
safe = []
while queue:
node = queue.popleft()
safe.append(node)
for prev in reverse_graph[node]:
in_degree[prev] -= 1
if in_degree[prev] == 0:
queue.append(prev)
return sorted(safe)
Solution
Step 1: Initialize in-degree and reverse graph
Graph has edges: 0->1, 1->2, 2->3, 3->none. So in_degree = [1,1,1,0], reverse_graph = [[],[0],[1],[2]].Step 2: Process queue starting with nodes having in-degree 0
Start with node 3 in queue. Pop 3, safe=[3]. Decrement in_degree of 2 to 0, add 2 to queue. Pop 2, safe=[3,2]. Decrement in_degree of 1 to 0, add 1. Pop 1, safe=[3,2,1]. Decrement in_degree of 0 to 0, add 0. Pop 0, safe=[3,2,1,0].Final Answer:
Option C -> Option CQuick Check:
All nodes lead to terminal node 3, so all are safe [OK]
- Forgetting to sort final safe list
- Miscounting in-degree initialization
- Off-by-one errors in queue processing
n courses labeled from 1 to n and a list of prerequisite pairs where each pair [a, b] means you must take course a before course b. You want to find the minimum number of semesters needed to complete all courses if you can take any number of courses in parallel as long as their prerequisites are met. Which algorithmic approach guarantees finding the minimum semesters efficiently?Solution
Step 1: Understand the problem constraints
The problem requires scheduling courses respecting prerequisites and minimizing semesters, allowing parallel courses per semester.Step 2: Identify the suitable algorithm
Kahn's Algorithm (topological sort with BFS) processes nodes with zero in-degree in batches (levels), naturally modeling semesters and ensuring minimal semesters.Final Answer:
Option C -> Option CQuick Check:
Level-by-level BFS matches semesters needed [OK]
- Thinking greedy picking minimal prerequisites works
- Confusing DFS order with minimal semester scheduling
- Trying exponential DP without pruning
Solution
Step 1: Understand problem constraints
The problem requires verifying if exactly one sequence matches all partial orderings, which is a classic unique topological order problem.Step 2: Identify suitable algorithm
Brute force is inefficient; greedy and DP approaches do not guarantee correctness or uniqueness checks. DFS postorder topological sort with cycle detection and uniqueness verification efficiently solves the problem.Final Answer:
Option D -> Option DQuick Check:
DFS topological sort with uniqueness check is standard for unique sequence reconstruction [OK]
- Assuming greedy or DP can guarantee uniqueness
- Trying brute force despite factorial complexity
Solution
Step 1: Analyze graph reversal and in-degree computation
Reversing the graph and computing in-degree requires iterating over all edges once, O(E).Step 2: Analyze BFS processing
Each node is enqueued and dequeued at most once, and each edge is considered once when decrementing in-degree, total O(V + E).Final Answer:
Option A -> Option AQuick Check:
Linear time in vertices and edges matches BFS and graph reversal [OK]
- Assuming nested loops cause O(V*E)
- Confusing sorting cost as dominant
- Forgetting BFS processes each edge once
Solution
Step 1: Understand reuse impact on matrix construction
Allowing reuse means elements can appear multiple times, so positions must reflect frequency, not just order.Step 2: Adjust algorithm to track counts and assign positions accordingly
Topological order alone does not handle multiple occurrences; tracking counts and assigning positions based on frequency is necessary.Final Answer:
Option C -> Option CQuick Check:
Frequency tracking ensures correct placement of repeated elements [OK]
- Assuming reuse needs no algorithm change
- Ignoring frequency of elements
- Replacing topological sort unnecessarily
