Find the Closest Marked Node - Problem

You are given a positive integer n which is the number of nodes of a 0-indexed directed weighted graph and a 0-indexed 2D array edges where edges[i] = [ui, vi, wi] indicates that there is an edge from node ui to node vi with weight wi.

You are also given a node s and a node array marked; your task is to find the minimum distance from s to any of the nodes in marked.

Return an integer denoting the minimum distance from s to any node in marked or -1 if there are no paths from s to any of the marked nodes.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, edges = [[0,1,5],[0,2,3],[1,3,2],[2,3,4]], s = 0, marked = [2,3]
Output: 3
💡 Note: Shortest path from node 0 to any marked node: 0→2 has distance 3, 0→1→3 has distance 7, so minimum is 3
Example 2 — No Path Available
$ Input: n = 3, edges = [[0,1,2]], s = 0, marked = [2]
Output: -1
💡 Note: No path exists from node 0 to marked node 2, so return -1
Example 3 — Source is Marked
$ Input: n = 2, edges = [[0,1,5]], s = 0, marked = [0]
Output: 0
💡 Note: Source node 0 is itself marked, so distance is 0

Constraints

  • 2 ≤ n ≤ 105
  • 1 ≤ edges.length ≤ 105
  • edges[i].length == 3
  • 0 ≤ ui, vi ≤ n - 1
  • 1 ≤ wi ≤ 106
  • 0 ≤ s ≤ n - 1
  • 1 ≤ marked.length ≤ n

Visualization

Tap to expand
Find the Closest Marked Node INPUT 0 (start) 1 2 marked 3 marked 5 3 2 4 n = 4 s = 0 marked=[2,3] edges: [0,1,5],[0,2,3] [1,3,2],[2,3,4] ALGORITHM STEPS 1 Build Adjacency List Create graph from edges 2 Init Dijkstra dist[s]=0, others=INF 3 Process Priority Queue Relax edges, update dist 4 Find Min Marked Dist Check all marked nodes Distance Array (from node 0) 0 1 2 3 0 5 3 7 min(dist[2], dist[3]) = min(3, 7) FINAL RESULT 0 2 3 1 3 Shortest path: 0 ---> 2 Distance: 3 (direct edge) OUTPUT 3 Key Insight: Dijkstra's algorithm finds shortest paths from source to ALL nodes in O((V+E)logV). After running Dijkstra once from s, simply iterate through marked[] and return the minimum distance. If all marked nodes have distance = INF, return -1 (unreachable). TutorialsPoint - Find the Closest Marked Node | Optimal Solution (Dijkstra)
Asked in
Google 42 Amazon 38 Microsoft 31 Meta 25
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen