Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Time for a signal to reach every node

Medium · Target 25 minutes · Graphs · Type asked atGoogleOptiver

A network has n nodes labelled 1 to n. Each entry [u, v, w] of times is a one-way link: a signal sent from u reaches v after w units of time. A signal is sent from node k. Return the time at which every node has received it, or −1 if some node never does.

Examples

InputOutputWhy
times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]], n = 4, k = 22Node 4 is reached last, through 3, at time 2.
times = [[1, 2, 5], [1, 3, 1], [3, 2, 1]], n = 3, k = 12The route through 3 beats the direct link to 2.
times = [[1, 2, 1]], n = 2, k = 2-1The only link points the wrong way.

Constraints

  • 1 ≤ n ≤ 100
  • 1 ≤ |times| ≤ 6000
  • 0 ≤ w ≤ 100
  • There may be several links between the same pair of nodes

Hints

Hint 1

The answer is the largest of the shortest travel times from k to every node. So the problem is single-source shortest paths.

Hint 2

Breadth-first search finds shortest paths only when every edge costs the same. With weights, a node discovered early may still be reached sooner by a longer chain of cheaper links.

Hint 3

Dijkstra: keep a heap of (time, node). Pop the smallest; the first time a node is popped, its time is final, because every other route reaches it through a node that is no nearer. Push its neighbours with their tentative times.

Where people lose marks

  • Marking a node as done when it is pushed rather than when it is popped. A later, cheaper route to it would then be ignored, which is breadth-first search with weights, and wrong.
  • Forgetting parallel links between the same two nodes: an adjacency list keeps all of them, and the heap picks the cheapest automatically.
  • Returning the time of the last node popped without checking that every node was reached. Unreached nodes never appear in the heap.
  • Indexing nodes from 0 when the input labels them from 1.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.