← Whiteboard questions

Network Delay Time

Find the shortest time for water to reach every junction

DSA, Medium, Advanced Graphs

Which structure or algorithm, and what does it cost.

Water flows through n junctions numbered 0 to n - 1. Each triple [a, b, w] in pipes is a one-way pipe: water that reaches junction a arrives at junction b exactly w minutes later. A valve at junction source opens at minute 0. Water enters every pipe leaving a junction as soon as it arrives there. Return the minute when every junction has water. Return -1 if some junction never gets water.

Examples

Input n = 5, pipes = [[0,1,4],[0,2,9],[1,2,3],[2,3,2],[1,3,8],[3,4,5]], source = 0
Output 14
Why water reaches junctions 1 to 4 at minutes 4, 7, 9 and 14, and 14 is the last.
Input n = 4, pipes = [[0,1,2],[2,3,1]], source = 0
Output -1
Why no pipe leads from the source to junctions 2 and 3.
Input n = 1, pipes = [], source = 0
Output 0
Why the source junction already has water at minute 0.

Constraints

Your answer must contain

Target Aim for O((n + r) log n) time and O(n + r) memory, where r is the number of pipes.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Water takes its fastest route to each junction. Which junction does the valve reach first, and how does that help you find the next one?

Hint 2 the approach

Think of a wave spreading from the valve. Which junction's time can you be sure of first, and why can no other route beat it?

Hint 3 the key step

Keep a min-heap of time and junction. Pop the smallest, skip it if a faster time is known, and push better times for its neighbours. Answer: the largest time.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every path from the source to every junction and keep the fastest time for each. The number of paths grows exponentially with the number of pipes, so this only works for a handful of pipes.

Better method

Bellman-Ford: start with time 0 at the source and infinity elsewhere. Repeat n - 1 rounds. In each round, for every pipe [a, b, w], lower the time of b to the time of a plus w if that is smaller. This is simple and correct, but it costs O(n * r) time, which is up to 250 million steps here.

Best method

Keep the best known time for each junction and a min-heap of (time, junction) pairs. Start with (0, source). Pop the smallest pair. If its time is worse than the best known time for that junction, it is old, so skip it. Otherwise, for each pipe out of the junction, if time plus w beats the best known time of the next junction, store the new time and push it. The first time a junction is popped with its best time, that time is final. Any other route must pass through a junction still in the heap with an equal or larger time, and a pipe never takes negative time. This method is called Dijkstra's algorithm. The answer is the largest final time, or -1 if a junction was never reached.

Hand trace

Example 1: the times start as [0, inf, inf, inf, inf] and the heap holds (0, junction 0). Pop (0, 0): junction 1 gets 4 and junction 2 gets 9. Pop (4, 1): junction 2 improves to 7 and junction 3 gets 12. Pop (7, 2): junction 3 improves to 9. Pop (9, 2): this entry is old, because junction 2 already has 7, so skip it. Pop (9, 3): junction 4 gets 14. Pop (12, 3): old, skip. Pop (14, 4). The final times are [0, 4, 7, 9, 14] and the largest is 14.

Code

import heapq
def water_time(n, pipes, source):
    nxt = [[] for _ in range(n)]
    for a, b, w in pipes:
        nxt[a].append((b, w))
    dist = [float("inf")] * n           # best known minute for water to reach each junction
    dist[source] = 0
    heap = [(0, source)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                    # an older, slower entry
        for v, w in nxt[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(heap, (d + w, v))
    worst = max(dist)
    return -1 if worst == float("inf") else worst

Time and memory

O((n + r) log n) time: each pipe can push at most one entry, and each push or pop costs O(log n). O(n + r) memory for the pipe lists, the times and the heap, where r is the number of pipes.

Common mistakes

  • Marking a junction done when it is pushed, not when it is popped. A faster route found later can then never replace the first time.
  • Forgetting the unreachable case. If any time is still infinite at the end, return -1.
  • Using a plain queue instead of a heap. A long pipe can make the first route found slower than a later one.

Related problems

More Advanced Graphs problems
Network Delay Time: hints, walkthrough and Python solution