Tech Interview RoomStudy guides

Graphs

Shortest path in a weighted graph (network delay time). Compare BFS, Bellman-Ford and Dijkstra.

Advanced · 2 min read · Lesson 4 of 4 in Graphs

Problem

Directed edges (u, v, w) with non-negative travel times. A signal starts at node k: how long until all n nodes receive it (or -1 if some never do)? times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 → 2.

Pattern

Single-source shortest paths. Unweighted → BFS. Non-negative weights → Dijkstra with a priority queue. Negative weights → Bellman-Ford.

Approach 1: Plain BFS (wrong for weighted graphs)

BFS minimises the number of edges, not total weight: a path with 3 cheap edges can beat 1 expensive edge. Mentioning why it fails is part of the answer.

Approach 2: Bellman-Ford (O(V·E), handles negative weights)

Relax every edge V − 1 times.

java
import java.util.Arrays;

class DelayBellmanFord {
    static int networkDelay(int[][] times, int n, int k) {
        long[] dist = new long[n + 1];
        Arrays.fill(dist, Long.MAX_VALUE);
        dist[k] = 0;
        for (int round = 1; round < n; round++) {
            boolean changed = false;
            for (int[] e : times) {
                if (dist[e[0]] != Long.MAX_VALUE && dist[e[0]] + e[2] < dist[e[1]]) { dist[e[1]] = dist[e[0]] + e[2]; changed = true; }
            }
            if (!changed) break;                                 // early exit
        }
        long max = 0;
        for (int i = 1; i <= n; i++) max = Math.max(max, dist[i]);
        return max == Long.MAX_VALUE ? -1 : (int) max;
    }
}

Approach 3: Dijkstra with a PriorityQueue (O(E log V)) — optimal for non-negative weights

Always expand the closest unsettled node; skip stale queue entries ("lazy deletion").

java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

class DelayDijkstra {
    static int networkDelay(int[][] times, int n, int k) {
        List<List<int[]>> graph = new ArrayList<>();
        for (int i = 0; i <= n; i++) graph.add(new ArrayList<>());
        for (int[] e : times) graph.get(e[0]).add(new int[] {e[1], e[2]});

        int[] dist = new int[n + 1];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[k] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));   // {node, distance}
        pq.offer(new int[] {k, 0});
        while (!pq.isEmpty()) {
            int[] top = pq.poll();
            int u = top[0], d = top[1];
            if (d > dist[u]) continue;                           // stale entry
            for (int[] edge : graph.get(u)) {
                int v = edge[0], nd = d + edge[1];
                if (nd < dist[v]) { dist[v] = nd; pq.offer(new int[] {v, nd}); }
            }
        }
        int max = 0;
        for (int i = 1; i <= n; i++) max = Math.max(max, dist[i]);
        return max == Integer.MAX_VALUE ? -1 : max;
    }
}

class DelayDemo {
    public static void main(String[] args) {
        int[][] times = {{2, 1, 1}, {2, 3, 1}, {3, 4, 1}};
        System.out.println(DelayBellmanFord.networkDelay(times, 4, 2) + " " + DelayDijkstra.networkDelay(times, 4, 2));   // 2 2
        int[][] cheaperLonger = {{1, 2, 10}, {1, 3, 1}, {3, 4, 1}, {4, 2, 1}};
        System.out.println(DelayBellmanFord.networkDelay(cheaperLonger, 4, 1) + " " + DelayDijkstra.networkDelay(cheaperLonger, 4, 1));   // 3 3
        System.out.println(DelayDijkstra.networkDelay(new int[][] {{1, 2, 1}}, 3, 1));   // -1
    }
}

Feasible → optimal

BFS is wrong for weights; Bellman-Ford is O(V·E) and handles negative edges (and detects negative cycles with one more round); Dijkstra is O(E log V) for non-negative weights and is the expected answer.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): cheapest flight with at most K stops.

Dijkstra's greedy choice breaks with a stop limit; run Bellman-Ford for exactly K + 1 rounds using a copy of the distance array per round (so each round adds at most one edge), or BFS by levels with pruning. O(K·E).

Related (same pattern): path with minimum effort in a grid (minimise the largest step).

Dijkstra where the "distance" of a path is the maximum absolute height difference along it: nd = max(d, |h[next] - h[cur]|). Alternatively binary search the answer with a BFS feasibility check, or Union-Find over edges sorted by weight.