Minimum Time to Visit Disappearing Nodes
MEDIUMDescription
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.
Note that the graph might be disconnected and might contain multiple edges.
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 1:
Input: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5]
Output: [0,-1,4]
Explanation:

We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.
- For node 0, we don't need any time as it is our starting point.
- For node 1, we need at least 2 units of time to traverse
edges[0]. Unfortunately, it disappears at that moment, so we won't be able to visit it. - For node 2, we need at least 4 units of time to traverse
edges[2].
Example 2:
Input: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5]
Output: [0,2,3]
Explanation:

We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.
- For node 0, we don't need any time as it is the starting point.
- For node 1, we need at least 2 units of time to traverse
edges[0]. - For node 2, we need at least 3 units of time to traverse
edges[0]andedges[1].
Example 3:
Input: n = 2, edges = [[0,1,1]], disappear = [1,1]
Output: [0,-1]
Explanation:
Exactly when we reach node 1, it disappears.
Constraints:
1 <= n <= 5 * 1040 <= edges.length <= 105edges[i] == [ui, vi, lengthi]0 <= ui, vi <= n - 11 <= lengthi <= 105disappear.length == n1 <= disappear[i] <= 105
Approaches
Checkout 2 different approaches to solve Minimum Time to Visit Disappearing Nodes. Click on different approaches to view the approach and algorithm in detail.
Naive Dijkstra's Algorithm
This approach uses a basic implementation of Dijkstra's algorithm. It finds the shortest path from the source node 0 to all other nodes. The main characteristic of this naive version is how it selects the next node to process. At each step, it performs a linear scan across all nodes to find the unvisited one with the minimum current travel time. The core logic is adapted to handle the disappearance constraint: a path to a node is only considered if the arrival time is strictly less than the node's disappearance time. While correct, this method is inefficient due to the repeated linear scans.
Algorithm
- Graph Representation: Build an adjacency list from the
edgesarray.adj[i]will store a list of pairs, where each pair consists of a neighbor node and the edge weight (time). - Initialization: Create a
minTimearray of sizeninitialized to infinity, representing the shortest time from node 0. SetminTime[0] = 0. Also, create a booleanvisitedarray of the same size, initialized tofalse. - Iterative Search: Loop
ntimes. In each iteration:- Find the unvisited node
uwith the smallestminTimevalue. This requires a linear scan through allnnodes. - If no such node is found (all remaining unvisited nodes have infinite time), it means they are unreachable, so break the loop.
- Mark node
uas visited.
- Find the unvisited node
- Edge Relaxation: For each neighbor
vof the selected nodeu:- Calculate the time to reach
vthroughu:newTime = minTime[u] + weight(u, v). - Constraint Check: This new path is only considered if it's a valid visit (
newTime < disappear[v]) and it's a shorter path (newTime < minTime[v]). - If both conditions are met, update
minTime[v] = newTime.
- Calculate the time to reach
- Finalization: After the loops complete, iterate through the
minTimearray. Any value that is still infinity means the corresponding node is unreachable. Replace these values with-1.
The algorithm begins by converting the edge list into a more usable adjacency list format. It then initializes a minTime array to keep track of the shortest time to reach each node, with minTime[0] set to 0 and all others to a value representing infinity. The main part of the algorithm is a loop that runs up to n times. In each iteration, it searches for the unvisited node u that is currently closest to the source. Once u is found, it is marked as visited, and we try to "relax" its edges. For each neighbor v of u, we calculate the time it would take to reach v by passing through u. If this new time is less than disappear[v] and also less than the current minTime[v], we update minTime[v]. This process continues until all reachable nodes have been visited. Finally, any node with an infinite minTime is marked as unreachable (-1).
import java.util.*;
class Solution {
public int[] minimumTime(int n, int[][] edges, int[] disappear) {
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
for (int[] edge : edges) {
adj.get(edge[0]).add(new int[]{edge[1], edge[2]});
adj.get(edge[1]).add(new int[]{edge[0], edge[2]});
}
int[] minTime = new int[n];
Arrays.fill(minTime, Integer.MAX_VALUE);
minTime[0] = 0;
boolean[] visited = new boolean[n];
for (int count = 0; count < n; count++) {
int u = -1;
int t = Integer.MAX_VALUE;
// Find the unvisited node with the smallest time
for (int i = 0; i < n; i++) {
if (!visited[i] && minTime[i] < t) {
t = minTime[i];
u = i;
}
}
if (u == -1) {
break; // All remaining nodes are unreachable
}
visited[u] = true;
for (int[] edge : adj.get(u)) {
int v = edge[0];
int weight = edge[1];
int newTime = t + weight;
if (newTime < disappear[v] && newTime < minTime[v]) {
minTime[v] = newTime;
}
}
}
for (int i = 0; i < n; i++) {
if (minTime[i] == Integer.MAX_VALUE) {
minTime[i] = -1;
}
}
return minTime;
}
}
Complexity Analysis
Pros and Cons
- Conceptually simpler than the priority queue-based version.
- Easy to implement if one is not familiar with heap data structures.
- The time complexity of
O(N^2)is too slow for the given constraints (Nup to 5 * 10^4), and will result in a Time Limit Exceeded error.
Code Solutions
Checking out 3 solutions in different languages for Minimum Time to Visit Disappearing Nodes. Click on different languages to view the code.
class Solution {
public
int[] minimumTime(int n, int[][] edges, int[] disappear) {
List<int[]>[] g = new List[n];
Arrays.setAll(g, k->new ArrayList<>());
for (var e : edges) {
int u = e[0], v = e[1], w = e[2];
g[u].add(new int[]{v, w});
g[v].add(new int[]{u, w});
}
int[] dist = new int[n];
Arrays.fill(dist, 1 << 30);
dist[0] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b)->a[0] - b[0]);
pq.offer(new int[]{0, 0});
while (!pq.isEmpty()) {
var e = pq.poll();
int du = e[0], u = e[1];
if (du > dist[u]) {
continue;
}
for (var nxt : g[u]) {
int v = nxt[0], w = nxt[1];
if (dist[v] > dist[u] + w && dist[u] + w < disappear[v]) {
dist[v] = dist[u] + w;
pq.offer(new int[]{dist[v], v});
}
}
}
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = dist[i] < disappear[i] ? dist[i] : -1;
}
return ans;
}
}
Video Solution
Watch the video walkthrough for Minimum Time to Visit Disappearing Nodes
Similar Questions
5 related questions you might find useful
Algorithms:
Data Structures:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.