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?
  1. A. 2 -1
  2. B. 3 -1
  3. C. 2 1
  4. 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

Exams that ask this topic