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: Shortest Path ProblemInput:n=4, s=0, marked=[2,3]edges=[[0,1,5],[0,2,3],[1,3,2],[2,3,4]]0source12marked3marked5324Shortest Distances:0 → 1: distance = 50 → 2: distance = 3 ✓0 → 3: distance = 7Result: 3Dijkstra finds shortest path 0→2 with distance 3Early termination when first marked node is reached
Understanding the Visualization
1
Input Graph
Directed weighted graph with source node and marked destinations
2
Shortest Path Search
Use Dijkstra's algorithm to find minimum distances
3
Result
Return distance to closest marked node or -1 if unreachable
Key Takeaway
🎯 Key Insight: Use Dijkstra's algorithm with early termination - stop as soon as any marked destination is reached
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