Data Structures & Algorithms (Graph): Minimum Time to Visit Disappearing Nodes

April 17, 2026

There is an undirected graph of n nodes. You are given a 2D array edges, where edges[i] = [ui, vi, lengthi] describes an edge between node ui and node vi with a traversal time of lengthi units.

Additionally, you are given an array disappear, where disappear[i] denotes the time when the node i disappears from the graph and you won't be able to visit it.

Return the array answer, with answer[i] denoting the minimum units of time required to reach node i from node 0. If node i is unreachable from node 0 then answer[i] is -1.

Example: Emergency Fire Response

Imagine a fire station dispatching emergency response teams to different houses across a city. Roads connecting the locations have different travel times, and some houses may become completely engulfed in flames after a certain time, making them inaccessible.

Determine the earliest time an emergency team can reach each house, ensuring it arrives before that house becomes inaccessible.

Nodes
n = 9
Disappear
[20, 4, 8, 10, 9, 12, 9, 12, 15]
Edges
[0, 1, 2][0, 2, 5][1, 2, 1][1, 3, 4][2, 3, 2][2, 4, 6][3, 4, 1][3, 5, 5][4, 5, 2][4, 6, 3][5, 6, 2][5, 7, 4][6, 7, 2]
0disappears at 20—1disappears at 4—2disappears at 8—3disappears at 10—4disappears at 9—5disappears at 12—6disappears at 9—7disappears at 12—8disappears at 15—2514261523242
DispatchA fire station dispatches emergency teams to houses across the city. Some houses become engulfed in flames and inaccessible. House 8 has no road to the others.
1

Playground: Leetcode 3112


Basic Intuition

  1. We need to find the minimum time required to reach every node connected to the source node, provided it is within the accepted threshold.

  2. An edge list is not an efficient representation for this problem, as it requires scanning the entire list to identify the neighbours of a particular node. We can convert the edge list into an adjacency list, which allows us to directly access the neighbours of a node.

  3. An improvement in one node's shortest path can lead to improvements in other nodes' shortest distances. Therefore, whenever we discover a shorter path to a node, we need to explore its neighbours again using the updated distance. This is the core principle behind Shortest Path Faster algorithm.


Naive Approach: Shortest Path Faster Algorithm

We start from the source node and explore its neighbours. Whenever we find a shorter path to a node, we add it to a queue so that we can explore its neighbours using the updated distances.

Algorithm

1. Covert the input edge list into an adjacency list. Since the graph is undirected, 
   add each edge in both directions, so that each endpoint (node) is represented as 
   a neighbour of the other.

2. Create an "answer" array of size "n", initializing the minimum travel time for each 
   node to Infinity.
3. Set the minimum time of the source node to 0 and add it to the queue.

4. Continue processing until the queue becomes empty.
    5. Remove the oldest node from the queue and retrieve its current minimum travel time.
    6. Iterate over all outgoing neigbours of the current node along with their corresponding
       edge weights.
        7. For each neighbour, calculate the minimum travel time required to reach it through the 
           current node: "newTime = answer[currentNode] + edgeWeight". 
        8. If "newTime" is smaller than the existing minimum travel time of the neighbour and denotes
           not exceed the threshold, update its minimum travel time add the neighbour to the queue.

8. Replace the minimum travel time for all unreachable nodes from Infinity to -1.
9. Return the "answer" array.

Implementation

Language
1public int[] minimumTime(int n, int[][] edges, int[] disappear) {
2
3 // Step 1: Build an adjacency list to effective access
4 // the neighbours of each node.
5 List<int[]>[] graph = new ArrayList[n];
6 for (int i = 0; i < n; i++) {
7 graph[i] = new ArrayList<>();
8 }
9
10 for (int[] edge : edges) {
11
12 int u = edge[0];
13 int v = edge[1];
14 int weight = edge[2];
15
16 // Since the graph is undirected, add the edge
17 // to the adjacency list of both vertices.
18 graph[u].add(new int[]{v, weight});
19 graph[v].add(new int[]{u, weight});
20 }
21
22 // Step 2: Initialize the shortest known arrival time for
23 // for each node as infinity.
24 int[] answer = new int[n];
25 Arrays.fill(answer, Integer.MAX_VALUE);
26
27 // Use a FIFO queue to process nodes whose distances
28 // have been improved. A node can be enqueued multiple times.
29 Queue<Integer> queue = new LinkedList<>();
30
31 // The source node is reachable at time 0.
32 answer[0] = 0;
33 queue.offer(0);
34
35 // Step 3: Keep processing until no further distance
36 // improvements can be discovered.
37 while (!queue.isEmpty()) {
38
39 // Step 4: Process the oldest enqueued node.
40 int currentNode = queue.poll();
41
42 // Step 5: Explore all neighbours to check if we can reach
43 // them through a shorter valid path.
44 for (int[] neighbour : graph[currentNode]) {
45
46 int nextNode = neighbour[0];
47 int weight = neighbour[1];
48
49 // Step 6: Calculate the arrival time at the neighbour
50 // using the shortest known time to the current node.
51 int newTime = answer[currentNode] + weight;
52
53 // Step 7: Relax the edge if:
54 // 1. We discover a shorter arrival time
55 // 2. The neighbour is reached before it disappears.
56 if ( newTime < answer[nextNode] &&
57 newTime < disappear[nextNode] ) {
58
59 // Update the shortest known arrival time
60 // and enqueue the neighbour for further exploration.
61 answer[nextNode] = newTime;
62 queue.offer(nextNode);
63 }
64 }
65 }
66
67 // Step 8: Nodes whose distances remain infinity are unreachable
68 // or cannot be reached before disappearing.
69 for (int i = 0; i < n; i++) {
70 if (answer[i] == Math.MAX_VALUE) {
71 answer[i] = -1;
72 }
73 }
74
75 return answer;
76
77}
nodes
2514261523242012345678
answer · queue
disappear
0
20
1
4
2
8
3
10
4
9
5
12
6
9
7
12
8
15
answer not created
queueempty
graph
not created
Start with n = 9, the 13 roads, and disappear = [20, 4, 8, 10, 9, 12, 9, 12, 15].
1/81

Time Complexity

The time complexity depends on the the following operations:

  1. Initializing the adjacency list: We iterate over all vertices to initialize their adjacency lists, which takes O(V) time. We then iterate over all edges to populate the adjacency list. Since the graph is undirected, each edge is added to the adjacency lists of both endpoints. This takes O(E) time. Therefore, this takes O(V + E).

  2. Queue processing: A node can be enqueued and processed multiple times. Whenever we process a node, we explore all its neighbours. In the worst case, every single vertex gets updated and re-queued (V - 1) times. f every vertex is popped O(V) times and each pop checks all its outgoing edges, the sum of all edge checks across all vertices equals O(V * E). ------ Need to explore this more -----

  3. Converting unreachable nodes to -1: We iterate over the answer array once to identify unreachable nodes and update their values to -1. Since the array contains (V) elements, this takes O(V).

Hence, the overall time complexity is O(V + E) + O(V * E) + O(V) = O(V * E).

Space Complexity

The space complexity is primarily determined by three data structures:

  1. Adjacency list: Each of the (V) vertices requires an adjacency list. Each of the (E) edges is stored twice because the graph is undirected. This takes O(V + E).

  2. answer array: Since the array contains (V) elements, this takes O(V).

  3. Queue: In the standard SPFA implementation, we maintain an additional inQueue[] array. Whenever we enqueue a node, we mark it as present in the queue. We only enqueue it again after it has been removed from the queue. This ensures that at any given time, each vertex can appear in the queue at most once. This takes O(V).

Hence, the overall space complexity is O(V + E). ------ Need to explore this more -----


Key Observations

Since all edge weights are non-negative, processing the node with the smallest tentative arrival time guarantees that its shortest arrival time has been found. We can then explore its neighbours and attempt to improve their arrival times, provided they are reached before their respective disappearing times.

This is the core greedy principle behind Dijkstra's algorithm.


Suitable Approach: Dijkstra's Algorithm

Algorithm

Implementation

Time Complexity

Space Complexity