Data Structures & AlgorithmsHardProduct Company SDE · graph round
Problem: Dijkstra from 0 with edges (0,1,1), (1,3,2), (0,2,4), (2,3,1). Which vertex sequence is the shortest path from 0 to 3? Run the code.
Problem: Dijkstra from 0 with edges (0,1,1), (1,3,2), (0,2,4), (2,3,1). Which vertex sequence is the shortest path from 0 to 3? Run the code.
import heapq
g = {0: [(1, 1), (2, 4)], 1: [(3, 2)], 2: [(3, 1)], 3: []}
dist = {0: 0}
prev = {}
pq = [(0, 0)]
while pq:
d, u = heapq.heappop(pq)
if d > dist.get(u, float('inf')):
continue
for v, w in g[u]:
if d + w < dist.get(v, float('inf')):
dist[v] = d + w
prev[v] = u
heapq.heappush(pq, (dist[v], v))
path = [3]
while path[-1] != 0:
path.append(prev[path[-1]])
print(path[::-1])What is printed?- A. [0, 2, 3]
- B. [0, 1, 3]
- C. [0, 1, 2, 3]
- D. [0, 2, 1, 3]
Correct answer: B. [0, 1, 3]
The route 0-1-3 costs 3, while 0-2-3 costs 5. Storing parent pointers and walking back from the target recovers the path.
More Coding Interview Problems questions
- Problem: Is the graph with edges forming the 5-cycle 0-1-2-3-4-0 bipartite? And is the 4-cycle 0-1-2-3-0 bipartite? Run the BFS colouring…
- Problem: Tree with edges 0-1, 0-2, 1-3, 1-4, 2-5. How many nodes are in the subtree of node 1 (rooted at 0)? Run the DFS code. python…
- Problem: Which statement about Fenwick (binary indexed) trees is false?
- Problem: Items have small values (at most 1000 each, n = 100) but very large weights (up to 10^9), and capacity W = 10^9. Which DP is…
- Problem: For n = 10^5 elements and q = 10^5 queries, a sqrt-decomposition answers each query in O(sqrt n). Roughly how many elementary…
- Problem: How many scalar multiplications does the naive product of a 3 x 4 matrix and a 4 x 2 matrix need?