Practice
pos array after processing conditions = [[1,2],[1,3],[3,4]] with n=4?Solution
Step 1: Initialize graph and in-degree arrays
Edges: 1->2, 1->3, 3->4; in_degree: [0,0,1,1,1]Step 2: Process queue and assign positions
Queue starts with node 1 (in_degree 0). Assign pos[1]=0. Decrement in_degree of 2 and 3 to 0, enqueue both. Next, dequeue 2 (pos[2]=1), then dequeue 3 (pos[3]=2), decrement in_degree of 4 to 0, enqueue 4, assign pos[4]=3.Final Answer:
Option A -> Option AQuick Check:
Positions reflect valid topological order [OK]
- Swapping positions of nodes 2 and 3
- Off-by-one indexing in pos array
n = 3 and relations = [[1,3],[2,3]], what is the value of semester returned by the function?from collections import deque, defaultdict
def min_semesters_optimal(n, relations):
graph = defaultdict(list)
indegree = [0] * (n + 1)
for u, v in relations:
graph[u].append(v)
indegree[v] += 1
queue = deque([i for i in range(1, n + 1) if indegree[i] == 0])
semester = 0
processed = 0
while queue:
semester += 1
for _ in range(len(queue)):
course = queue.popleft()
processed += 1
for nei in graph[course]:
indegree[nei] -= 1
if indegree[nei] == 0:
queue.append(nei)
return semester if processed == n else -1
print(min_semesters_optimal(3, [[1,3],[2,3]]))Solution
Step 1: Initialize graph and indegree
Courses 1 and 2 have indegree 0, course 3 has indegree 2.Step 2: Process BFS levels
Semester 1: process courses 1 and 2 (both indegree 0), decrement indegree of 3 twice -> indegree[3] becomes 0, add 3 to queue. Semester 2: process course 3.Final Answer:
Option A -> Option AQuick Check:
Two BFS levels -> 2 semesters [OK]
- Counting each course as a separate semester
- Off-by-one error in semester increment
- Returning -1 incorrectly when all courses processed
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]) # Bug fixed here
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: Identify in-degree assignment error
In-degree should be assigned per node u, but the original code assigned in_degree[v] inside inner loop, overwriting multiple times incorrectly.Step 2: Correct assignment
It should be in_degree[u] = len(graph[u]) after inner loop completes, not in_degree[v].Final Answer:
Option D -> Option DQuick Check:
Incorrect in-degree causes wrong queue initialization and wrong safe nodes [OK]
- Confusing in-degree and out-degree assignment
- Assigning in-degree inside inner loop incorrectly
- Misusing loop variables for in-degree
n courses and m prerequisite relations?Solution
Step 1: Analyze graph traversal
Each course (node) is enqueued and dequeued at most once; each edge is visited once when decrementing indegree.Step 2: Combine node and edge processing
Total operations proportional to number of nodes plus edges -> O(n + m).Final Answer:
Option A -> Option AQuick Check:
Linear time in nodes and edges [OK]
- Assuming nested loops cause O(n*m)
- Confusing indegree updates as repeated scans
- Assuming dense graph means O(n^2) always
Solution
Step 1: Understand impact of cycles
Leaf trimming relies on tree properties (acyclic). Cycles cause infinite loops or incorrect leaf identification.Step 2: Modify algorithm to handle cycles
Detect cycles and remove edges to convert graph into a tree or forest, then apply leaf trimming to find centroids.Final Answer:
Option C -> Option CQuick Check:
Cycle removal is prerequisite for leaf trimming correctness [OK]
- Assuming leaf trimming works on cyclic graphs
- Using BFS from every node inefficiently
- Applying topological sort on undirected graph
