Network Delay Time – Solution & Complexity

1. Recognize the Pattern

The key pattern is: Dijkstra settles nodes by earliest signal arrival. Identify the state and invariant before coding.

2. Build the Algorithm

Advance one state transition at a time. Mark or update state before exploring dependent work.

3. Check Edge Cases

Test empty or minimal input, skewed shapes, duplicates where allowed, and impossible outcomes.

4. Solution and Complexity

Time: O((V + E) log V). Space: O(V + E).

def network_delay_time(times: list[list[int]], n: int, k: int) -> int:
    import heapq
    graph = [[] for _ in range(n + 1)]
    for source, target, weight in times: graph[source].append((weight, target))
    heap, distance = [(0, k)], {}
    while heap:
        elapsed, node = heapq.heappop(heap)
        if node in distance: continue
        distance[node] = elapsed
        for weight, neighbor in graph[node]:
            if neighbor not in distance: heapq.heappush(heap, (elapsed + weight, neighbor))
    return max(distance.values()) if len(distance) == n else -1

FAQ