PPractick

DSA interview question

Network Delay Time

Medium · Data structures · Topics: graph, dijkstra

The problem

A server cluster has n nodes labelled 1..n and directed links with transmission times. Node k broadcasts a signal. How long until every node has received it? Each node receives the signal at its shortest-path time from k, so the answer is the largest of those shortest times, or −1 if some node is unreachable. That's single-source shortest paths with non-negative weights: Dijkstra.

Example: times = [[2,1,1], [2,3,1], [3,4,1]], n = 4, k = 2 → 2.

Function signature

int networkDelayTime(const vector<array<int, 3>>& times, int n, int k);  // nodes 1..n; times {u, v, w}

Test cases

Input (times, n, k)OutputExplanation
([[2,1,1],[2,3,1],[3,4,1]], 4, 2)2Node 4 is last, at time 2
([[1,2,1],[2,3,2],[1,3,4]], 3, 1)31→2→3 beats the direct 4
([[1,2,1]], 2, 1)1
([[1,2,1]], 2, 2)-1Node 1 can't be reached from 2
([], 1, 1)0Only the source

(Confirm: links are directed; times are non-negative; the signal starts at time 0.)

How interviewers phrase it

Clarifying questions to ask

  1. Are links directed? (Yes.)
  2. Can times be zero? (Yes, but not negative.)
  3. Are nodes 1-indexed? (Yes.)

Follow-ups to expect

  1. "Why the maximum of the distances?"
  2. "Why Dijkstra?"
  3. "Could Bellman–Ford work?"
  4. "How do you detect unreachable nodes?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in