CP

743. Network Delay Time

MetricComplexityExplanation
TimeO((V+E)logV)O((V + E) \log V)Each edge relaxation may push to heap; heap ops are O(logV)O(\log V)
SpaceO(V+E)O(V + E)Adjacency list O(E)O(E), distance array O(V)O(V), heap up to O(E)O(E)
class Solution:
    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
        G = defaultdict(list)
        for u, v, w in times:
            G[u].append([v, w])
        
        W = [inf] * (n + 1)
        W[k] = 0
        heap = [(0, k)]

        while heap:
            w, node = heappop(heap)

            for nei, nei_w in G[node]:
                nw = w + nei_w
                if nw < W[nei]:
                    W[nei] = nw
                    heappush(heap, [nw, nei])

        result = max(W[1:])
        return -1 if result == inf else result
MetricComplexityExplanation
TimeO(VE)O(V \cdot E)n1n-1 iterations, each relaxing all EE edges
SpaceO(V)O(V)Distance array only
class Solution:
    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
        W = [inf] * (n + 1)
        W[k] = 0

        for _ in range(n - 1):
            for u, v, w in times:
                if W[u] + w < W[v]:
                    W[v] = W[u] + w

        result = max(W[1:])
        return result if result != inf else -1