Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the cheapest network latency to reach all nodes from node k (network delay = max shortest distance).
Problem: Find the cheapest network latency to reach all nodes from node k (network delay = max shortest distance).
import heapq
def delay(times, n, k):
adj = {i: [] for i in range(1, n + 1)}
for u, v, w in times: adj[u].append((v, w))
dist = {}; pq = [(0, k)]
while pq:
d, u = heapq.heappop(pq)
if u in dist: continue
dist[u] = d
for v, w in adj[u]:
if v not in dist: heapq.heappush(pq, (d + w, v))
return max(dist.values()) if len(dist) == n else -1
print(delay([(2, 1, 1), (2, 3, 1), (3, 4, 1)], 4, 2), delay([(1, 2, 1)], 2, 2))What is printed?- A. 2 -1
- B. 3 -1
- C. 2 1
- D. 1 -1
Correct answer: A. 2 -1
Lazy Dijkstra: the first time a node is popped its distance is final. From 2: node 1 and node 3 at 1, node 4 at 2 → the slowest is 2. In the second case the only edge goes 1 → 2, so from 2 node 1 is unreachable → −1. O(E log E).
More Coding Interview Problems questions
- Problem: Clone check – count how many nodes a BFS reaches from node 0 in a directed graph that contains a cycle. python from collections…
- Problem: Print a matrix in spiral order (clockwise from the top-left). cpp vector<int> spiral(vector<vector<int>>& m) { vector<int> out…
- Problem: Rotate an n × n image 90° clockwise in place. python def rotate(m): n = len(m) for i in range(n): for j in range(i + 1, n)…
- Problem: Set the whole row and column to 0 for every 0 in a matrix. python def zeroes(m): R, C = len(m), len(m[0]) rows = {r for r in…
- Problem: Find the element that appears more than n/2 times (guaranteed to exist) using Boyer–Moore voting. java static int majority(int[]…
- Problem: Sort an array of 0s, 1s and 2s in one pass (Dutch national flag). cpp void sort012(vector<int>& a) { int lo = 0, mid = 0, hi =…