Skip to content
DSA Patterns
Menu
Language
Shortest Path (Weighted)LC #7431 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Network Delay Time

Problem (restated)

A directed network of n nodes (1-indexed) and weighted edges times[i] = [u, v, w] (signal from u to v takes w). A signal starts at node k. Return the time for every node to receive it, or -1 if some node is unreachable.

Intuition

The time the last node hears the signal is the longest shortest-path from k. Weights are non-negative, so Dijkstra from k. Answer is max(dist[1..n]), or -1 if any dist is still infinite.

Approaches

Dijkstra from k

Unverified
Time O((n+E) log n)Space O(n+E)

Idea. Adjacency list of (v, w). dist[k] = 0, min-heap of (d, u). Pop the closest node; skip stale pops (d > dist[u]); relax dist[v] = d + w and push. Then take the max finite distance.

Walkthrough. n=4, k=2, edges 2→1 (1), 2→3 (1), 3→4 (1). Distances 1,0,1,2. Max 2.

Trade-offs. The template. Unreachable nodes stay ∞ → -1. BFS would be wrong: a cheap two-edge path can beat a costly one-edge path.

Solution
Show helper code
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
/** Real binary min-heap priority queue: O((V+E) log V). */
export function networkDelayTime(times: number[][], n: number, k: number): number {
  const adj: [number, number][][] = Array.from({ length: n + 1 }, () => []);
  for (const [u, v, w] of times) adj[u]!.push([v, w]);
  const dist = new Array<number>(n + 1).fill(Infinity);
  dist[k] = 0;
  const pq = new Heap<[number, number]>((a, b) => a[0]! < b[0]!);
  pq.push([0, k]);
  while (pq.size) {
    const [d, u] = pq.pop();
    if (d > dist[u]!) continue;
    for (const [v, w] of adj[u]!) {
      if (d + w < dist[v]!) {
        dist[v] = d + w;
        pq.push([dist[v]!, v]);
      }
    }
  }
  let ans = 0;
  for (let i = 1; i <= n; i++) {
    if (dist[i] === Infinity) return -1;
    ans = Math.max(ans, dist[i]!);
  }
  return ans;
}
/** Real binary min-heap priority queue: O((V+E) log V). */
export function networkDelayTime(times: number[][], n: number, k: number): number {
  const adj: [number, number][][] = Array.from({ length: n + 1 }, () => []);
  for (const [u, v, w] of times) adj[u]!.push([v, w]);
  const dist = new Array<number>(n + 1).fill(Infinity);
  dist[k] = 0;
  const pq = new Heap<[number, number]>((a, b) => a[0]! < b[0]!);
  pq.push([0, k]);
  while (pq.size) {
    const [d, u] = pq.pop();
    if (d > dist[u]!) continue;
    for (const [v, w] of adj[u]!) {
      if (d + w < dist[v]!) {
        dist[v] = d + w;
        pq.push([dist[v]!, v]);
      }
    }
  }
  let ans = 0;
  for (let i = 1; i <= n; i++) {
    if (dist[i] === Infinity) return -1;
    ans = Math.max(ans, dist[i]!);
  }
  return ans;
}

Template connection

Plain Dijkstra: min-heap by distance, relax on pop, skip stale entries. LC 1976 is the same loop plus path counts.

Reflection

  • Dijkstra from k with a min-heap of (time, node). The first pop of a node is its shortest time. The answer is the latest finite time.
  • Any node still unreachable is −1. There are no negative weights. A later, larger time for the same node is a stale pop.
  • n = 1 answers 0. No edges and n > 1 answers −1.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 7
1/7

Weighted shortest path. Edges: S→A 1, S→B 4, A→B 1, A→T 7, B→T 1. BFS hops are the wrong metric.

14171S0A∞B∞T∞
Stateheap=[(0, S)]

dist[S]=0 · min-heap

Key:CurrentActive rangeMatchSettled