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
Solution
Step 1: Understand problem constraints and graph properties
The problem requires tracking maximum color counts along paths in a directed graph, which may contain dependencies and cycles.Step 2: Identify suitable algorithm
Topological sort linearizes nodes respecting dependencies, enabling iterative DP to accumulate color counts efficiently without redundant recomputation.Final Answer:
Option C -> Option CQuick Check:
Topological sort + DP handles dependencies and cycles correctly [OK]
- Assuming greedy or simple DFS suffices without cycle detection
from collections import defaultdict, deque
def largestPathValue(colors, edges):
n = len(colors)
graph = defaultdict(list)
indegree = [0] * n
for u, v in edges:
graph[u].append(v)
indegree[v] += 1
dp = [[0]*26 for _ in range(n)]
queue = deque([i for i in range(n) if indegree[i] == 0])
count = 0
max_color_value = 0
while queue:
node = queue.popleft()
count += 1
c_index = ord(colors[node]) - ord('a')
dp[node][c_index] += 1
max_color_value = max(max_color_value, dp[node][c_index])
for nei in graph[node]:
for i in range(26):
dp[nei][i] = max(dp[nei][i], dp[node][i])
indegree[nei] -= 1
if indegree[nei] == 0:
queue.append(nei)
if count != n:
return -1 # cycle detected
return max_color_value
Solution
Step 1: Understand dp update logic
dp[nei][i] should aggregate max counts from predecessors, but the code overwrites dp[nei][i] without adding the neighbor's own color count.Step 2: Identify bug
The bug is that dp[nei][i] = max(dp[nei][i], dp[node][i]) does not add the neighbor's own color count, causing undercounting.Final Answer:
Option B -> Option BQuick Check:
Incorrect aggregation leads to wrong max color values [OK]
- Not aggregating color counts from neighbors properly
Solution
Step 1: Identify cycle problem
Allowing revisits means cycles can cause infinite loops if not tracked per path.Step 2: Solution approach
Maintain a visited set per path to avoid revisiting nodes already in the current path, preventing cycles.Final Answer:
Option A -> Option AQuick Check:
Global visited set disallows legitimate different paths; per-path visited set is needed [OK]
- Using global visited set incorrectly
- Assuming no cycles without checks
Solution
Step 1: Identify disconnected components
Courses with no prerequisites form disconnected subgraphs with zero in-degree nodes.Step 2: Initialize queue with all zero in-degree nodes
Queue must include all such nodes to process all components and produce a full valid order.Step 3: Process BFS as usual
Processing all zero in-degree nodes ensures all courses are included in the order.Final Answer:
Option A -> Option AQuick Check:
Queue initialization with all zero in-degree nodes covers disconnected graphs [OK]
- Starting BFS from a single node only
- Ignoring disconnected components
- Skipping cycle detection in DFS
