LeetCode Problem Workspace

Network Delay Time

Find the minimum time for a signal to travel to all nodes in a directed graph or determine if it's impossible.

category

5

Topics

code_blocks

5

Code langs

hub

3

Related

Practice Focus

Medium · Graph traversal with depth-first search

bolt

Answer-first summary

Find the minimum time for a signal to travel to all nodes in a directed graph or determine if it's impossible.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Graph traversal with depth-first search

Try AiBox Copilotarrow_forward

This problem involves sending a signal from a given node to all nodes in a network, and determining the minimum time for the signal to reach every node. You must apply graph traversal techniques like Depth-First Search (DFS) or Breadth-First Search (BFS) to find the solution. If all nodes cannot receive the signal, return -1.

Problem Statement

You are given a network of n nodes, each labeled from 1 to n. A list of travel times, represented as directed edges times[i] = (ui, vi, wi), is provided, where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from the source to the target. The goal is to send a signal from a specified node k and determine the minimum time it takes for all n nodes to receive the signal.

If it is impossible for all nodes to receive the signal, the function should return -1. Otherwise, the output should be the time it takes for the signal to reach every node. In cases where there are unreachable nodes, the solution must account for those cases by returning -1.

Examples

Example 1

Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2

Output: 2

Example details omitted.

Example 2

Input: times = [[1,2,1]], n = 2, k = 1

Output: 1

Example details omitted.

Example 3

Input: times = [[1,2,1]], n = 2, k = 2

Output: -1

Example details omitted.

Constraints

  • 1 <= k <= n <= 100
  • 1 <= times.length <= 6000
  • times[i].length == 3
  • 1 <= ui, vi <= n
  • ui != vi
  • 0 <= wi <= 100
  • All the pairs (ui, vi) are unique. (i.e., no multiple edges.)

Solution Approach

Graph Traversal with DFS

Start by representing the network as a graph, using an adjacency list. You can use Depth-First Search (DFS) to explore the graph from the starting node k, tracking the signal's arrival time at each node. Ensure to update the minimum time as you traverse edges to other nodes.

Priority Queue for Optimized Search

Instead of DFS, a more efficient approach is to use Dijkstra's algorithm with a priority queue (heap). This allows for an optimized search of the shortest path, ensuring the signal reaches nodes in the minimal time, while taking care of possible cycles and unreachable nodes.

BFS for Uniform Weight Graph

If the graph is uniform, with all edge weights equal, a Breadth-First Search (BFS) can be an effective strategy. By traversing level by level, BFS can help determine the shortest time required for the signal to reach all nodes, stopping once all nodes are covered or confirming if some are unreachable.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

The time complexity of the solution depends on the method chosen. Using DFS or BFS, the time complexity is O(V + E), where V is the number of nodes and E is the number of edges. With a priority queue, using Dijkstra's algorithm, the complexity is O((V + E) log V), which is more efficient for graphs with non-uniform weights. The space complexity for DFS and BFS is O(V), while the priority queue-based approach uses O(V + E) space for the graph representation and priority queue management.

What Interviewers Usually Probe

  • The candidate is expected to demonstrate knowledge of graph traversal methods and the ability to optimize with a priority queue or BFS.
  • Be prepared for candidates to compare DFS and BFS as options, with an emphasis on using the most efficient method for large input sizes.
  • A successful answer should include handling edge cases, such as unreachable nodes or cycles, and the reasoning for selecting the approach used.

Common Pitfalls or Variants

Common pitfalls

  • Failing to correctly handle the case where not all nodes can receive the signal, leading to an incorrect return value of -1.
  • Incorrectly assuming all graphs are uniform, which may lead to inefficient solutions or improper use of BFS/Dijkstra.
  • Not accounting for the possibility of cycles in the graph, which could lead to an infinite loop or incorrect time calculations.

Follow-up variants

  • A variation of this problem could involve multiple source nodes for the signal, testing the candidate's ability to modify their approach to handle additional starting points.
  • Another variant could involve a directed graph with negative edge weights, which would require considering algorithms like Bellman-Ford instead of Dijkstra or BFS.
  • The problem could also be modified by adding additional constraints, such as limiting the number of allowed edges, which could test the candidate's ability to optimize graph traversal techniques.

FAQ

How do I approach the 'Network Delay Time' problem?

Start by choosing a graph traversal method like DFS or BFS. For more efficiency with weighted edges, use Dijkstra's algorithm with a priority queue.

What is the time complexity of this problem?

The time complexity depends on the approach: DFS/BFS is O(V + E), and Dijkstra's algorithm with a priority queue is O((V + E) log V).

Can I use BFS for graphs with different edge weights?

BFS works best for graphs with uniform edge weights. For non-uniform weights, Dijkstra's algorithm is more efficient.

How do I handle unreachable nodes in 'Network Delay Time'?

Make sure to check for nodes that remain unvisited after the traversal and return -1 if not all nodes can receive the signal.

What makes DFS unsuitable for large networks in this problem?

DFS can be inefficient for large networks, especially when dealing with cycles or non-uniform edge weights. Dijkstra's algorithm with a priority queue offers better performance for such cases.

terminal

Solution

Solution 1: Naive Dijkstra Algorithm

We define $\textit{g}[u][v]$ to represent the edge weight from node $u$ to node $v$. If there is no edge between node $u$ and node $v$, then $\textit{g}[u][v] = +\infty$.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
        g = [[inf] * n for _ in range(n)]
        for u, v, w in times:
            g[u - 1][v - 1] = w
        dist = [inf] * n
        dist[k - 1] = 0
        vis = [False] * n
        for _ in range(n):
            t = -1
            for j in range(n):
                if not vis[j] and (t == -1 or dist[t] > dist[j]):
                    t = j
            vis[t] = True
            for j in range(n):
                dist[j] = min(dist[j], dist[t] + g[t][j])
        ans = max(dist)
        return -1 if ans == inf else ans

Solution 2: Heap-Optimized Dijkstra Algorithm

We can use a priority queue (heap) to optimize the naive Dijkstra algorithm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
        g = [[inf] * n for _ in range(n)]
        for u, v, w in times:
            g[u - 1][v - 1] = w
        dist = [inf] * n
        dist[k - 1] = 0
        vis = [False] * n
        for _ in range(n):
            t = -1
            for j in range(n):
                if not vis[j] and (t == -1 or dist[t] > dist[j]):
                    t = j
            vis[t] = True
            for j in range(n):
                dist[j] = min(dist[j], dist[t] + g[t][j])
        ans = max(dist)
        return -1 if ans == inf else ans
Network Delay Time Solution: Graph traversal with depth-first sear… | LeetCode #743 Medium