Practice
from collections import defaultdict
import heapq
def findCheapestPrice(n, flights, src, dst, K):
graph = defaultdict(list)
for u, v, w in flights:
graph[u].append((v, w))
heap = [(0, src, 0)] # cost, node, stops
while heap:
cost, node, stops = heapq.heappop(heap)
if node == dst:
return cost
if stops <= K:
for nei, price in graph[node]:
heapq.heappush(heap, (cost + price, nei, stops + 1))
return -1
print(findCheapestPrice(n, flights, src, dst, K))Solution
Step 1: Trace initial heap and first pop
Heap starts with (0,0,0). Pop (0,0,0), node=0, stops=0 <= K=1, push neighbors: (100,1,1) and (500,2,1).Step 2: Pop next smallest cost
Pop (100,1,1), node=1, stops=1 <= K=1, push neighbor: (200,2,2). Next pop is (200,2,2) but stops=2 > K, so not pushed further. Then pop (500,2,1), node=2 matches dst, return cost=500. But since (200,2,2) is invalid (stops>1), the first valid arrival at dst is (500,2,1).Final Answer:
Option B -> Option BQuick Check:
Stops constraint prunes cheaper but invalid path; returns 200 [OK]
- Returning 500 ignoring cheaper path with too many stops
- Returning -1 assuming no path
- Confusing stops count with edges
Solution
Step 1: Understand the problem requires shortest paths with weighted edges
BFS assumes equal edge weights and cannot handle varying weights correctly, so it fails here.Step 2: Identify that Dijkstra's algorithm uses a priority queue to always pick the next closest node, guaranteeing optimal shortest paths in graphs with non-negative weights
DFS with path relaxation is inefficient and does not guarantee optimality without pruning, and greedy edge picking ignores path costs.Final Answer:
Option A -> Option AQuick Check:
Dijkstra handles weighted shortest paths optimally [OK]
- Assuming BFS works for weighted graphs
- Thinking DFS with relaxation is efficient
- Believing greedy edge picking always works
times = [[1,2,1],[2,3,2],[1,3,4]], n = 3, and k = 1, what is the final returned value?Solution
Step 1: Initialize distances with dist[1]=0, dist[2]=inf, dist[3]=inf
After first iteration, relax edges: dist[2]=1 (via 1->2), dist[3]=4 (via 1->3)Step 2: Second iteration relaxes edge 2->3: dist[3] updated to dist[2]+2=3 which is less than 4
No further updates after this iteration, so loop breaks earlyFinal Answer:
Option B -> Option BQuick Check:
Maximum distance is 3, so return 3 [OK]
- Not updating dist[3] to 3 after second iteration
- Returning initial max distance 4 instead of updated 3
- Confusing iteration count and stopping early
valid_tree function for a graph with n nodes and e edges, and why?Solution
Step 1: Analyze BFS traversal
BFS visits each node once and explores each edge once in adjacency lists.Step 2: Consider edges and nodes
Time complexity is proportional to number of nodes plus edges, O(n + e).Final Answer:
Option C -> Option CQuick Check:
Standard BFS complexity is O(n + e) [OK]
- Assuming BFS is O(n^2) due to adjacency matrix
- Confusing sorting cost with BFS traversal
Solution
Step 1: Identify BFS visits each cell at most once
Each cell is enqueued and dequeued once, so total operations proportional to number of cells.Step 2: Each cell checks up to 4 neighbors in constant time
Neighbor checks are constant per cell, so total is O(m*n).Final Answer:
Option C -> Option CQuick Check:
Linear in grid size, no repeated visits [OK]
- Assuming BFS revisits cells multiple times
- Confusing rows+cols with total cells
- Ignoring constant neighbor checks
