Data Structures & AlgorithmsVery hardProduct company OA
Problem: Two versions of Dijkstra. The second marks a vertex as finished the moment it is first PUSHED and never updates it again.
Problem: Two versions of Dijkstra. The second marks a vertex as finished the moment it is first PUSHED and never updates it again.
import heapq
def dijkstra(g, s, mark_on_push):
dist = {s: 0}; done = set(); h = [(0, s)]
if mark_on_push: done.add(s)
while h:
d, u = heapq.heappop(h)
if not mark_on_push:
if u in done: continue
done.add(u)
for v, w in g[u]:
if mark_on_push:
if v in done: continue
done.add(v); dist[v] = d + w; heapq.heappush(h, (d + w, v))
elif d + w < dist.get(v, 10**9):
dist[v] = d + w; heapq.heappush(h, (d + w, v))
return dist
g = {"S": [("A", 10), ("B", 1)], "B": [("C", 1)], "C": [("A", 1), ("T", 20)], "A": [("T", 2)], "T": []}
print(dijkstra(g, "S", False)["T"], dijkstra(g, "S", True)["T"])What is printed?- A. 5 5
- B. 22 5
- C. 5 22
- D. 13 22
Correct answer: C. 5 22
Marking on push freezes A at 10 (direct edge S → A) before the cheaper route S → B → C → A of cost 3 is found, and C's edge to A is ignored. C is popped before A, so T is first pushed – and frozen – with 2 + 20 = 22; the later route through A is ignored too. The correct version marks on POP, so A's distance can still drop: S → B → C → A → T = 1 + 1 + 1 + 2 = 5. Finalise a vertex only when it leaves the heap with its minimum key.
More Coding Interview Problems questions
- Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches…
- Problem: Single machine, jobs (name, duration, due time); lateness = finish − due. Minimise the MAXIMUM lateness. Compare…
- Problem: Two sorted price lists; list the 6 smallest sums a[i] + b[j] without generating all pairs (heap of frontier cells with a…
- Problem: Find all critical links (bridges) and critical routers (articulation points) with one DFS using discovery times and low-links…
- Problem: A drone must fly every route leg exactly once starting at P, choosing the alphabetically smallest destination whenever possible…
- Problem: Assign interns to projects; intern u may take only projects in adj[u], each project at most one intern. Maximum bipartite…