#3112

Minimum Time to Visit Disappearing Nodes

Medium
ArrayGraph TheoryHeap (Priority Queue)Shortest PathGraph TraversalPriority QueueDijkstra's Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(E log V)
Space
O(1)
O(V)
💡

Intuition

Time O(E log V)Space O(V)

We can use Dijkstra's algorithm to find the shortest path to each node while considering the disappearance times. This approach efficiently finds the minimum time to reach each node by prioritizing paths based on their traversal time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a priority queue and a result array with -1 for all nodes except the starting node (node 0) which is set to 0.
  2. 2Step 2: Push the starting node into the priority queue with a time of 0.
  3. 3Step 3: While the priority queue is not empty, pop the node with the smallest time. If this time is less than the disappearance time, update the result for that node and push its neighbors into the queue with updated times.
solution.py26 lines
1# Full working Python code
2import heapq
3from collections import defaultdict
4
5def min_time_to_visit(n, edges, disappear):
6    graph = defaultdict(list)
7    for u, v, length in edges:
8        graph[u].append((v, length))
9        graph[v].append((u, length))
10
11    result = [-1] * n
12    result[0] = 0
13    pq = [(0, 0)]  # (time, node)
14
15    while pq:
16        time, node = heapq.heappop(pq)
17        if time >= disappear[node]:
18            continue
19        for neighbor, travel_time in graph[node]:
20            new_time = time + travel_time
21            if new_time < disappear[neighbor] and (result[neighbor] == -1 or new_time < result[neighbor]):
22                result[neighbor] = new_time
23                heapq.heappush(pq, (new_time, neighbor))
24
25    return result
26

Complexity note: The time complexity is O(E log V) because we use a priority queue to efficiently get the next node with the smallest time, where E is the number of edges and V is the number of nodes.

  • 1Use Dijkstra's algorithm for shortest paths with constraints.
  • 2Consider node disappearance times when updating paths.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.