MediumNo. 0743

Network Delay Time — LeetCode 743 Python Solution

Topics
Depth-First Search, Breadth-First Search, Graph, Shortest Path, Heap (Priority Queue)
On a study list
NeetCode 150
Reading time
3 min

The problem

You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.

Example

Input
times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output
2

Python solution

PythonSolution
class Solution:
    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
        g = [[inf] * n for _ in range(n)]
        for u, v, w in times:
            g[u - 1][v - 1] = w
        dist = [inf] * n
        dist[k - 1] = 0
        vis = [False] * n
        for _ in range(n):
            t = -1
            for j in range(n):
                if not vis[j] and (t == -1 or dist[t] > dist[j]):
                    t = j
            vis[t] = True
            for j in range(n):
                dist[j] = min(dist[j], dist[t] + g[t][j])
        ans = max(dist)
        return -1 if ans == inf else ans

Complexity

Time
O(n2 + m)
Space · auxiliary
O(n2)

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 743. Network Delay Time is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 743. Network Delay Time?

LeetCode 743. Network Delay Time is rated Medium on LeetCode.

What is the time complexity of LeetCode 743. Network Delay Time?

The Python solution on this page runs in O(n2 + m).

What is the space complexity of LeetCode 743. Network Delay Time?

The Python solution on this page uses O(n2) auxiliary space.

What topics does LeetCode 743. Network Delay Time cover?

LeetCode 743. Network Delay Time is tagged Depth-First Search, Breadth-First Search, Graph, Shortest Path and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.