Find the Closest Marked Node - Problem

Imagine you're a delivery driver navigating a city with one-way streets, and you need to find the shortest route to any of your delivery destinations from your current location.

You're given a directed weighted graph representing a city where:

  • There are n intersections (nodes) numbered from 0 to n-1
  • Each edge [u, v, w] represents a one-way street from intersection u to intersection v with travel time w
  • You start at intersection s
  • You have multiple possible destinations stored in the marked array

Your goal: Find the minimum travel time from your starting point s to reach any of the marked destinations. If no destinations are reachable, return -1.

Example: If you're at intersection 0 and need to deliver to intersections [2, 3], find the shortest path to whichever destination is closest.

Input & Output

example_1.py β€” Basic Graph
$ Input: n = 4, edges = [[0,1,1],[1,2,2],[0,3,4]], s = 0, marked = [2,3]
β€Ί Output: 3
πŸ’‘ Note: From node 0, we can reach node 2 with distance 1+2=3 (path: 0β†’1β†’2) and node 3 with distance 4 (path: 0β†’3). The minimum distance to any marked node is 3.
example_2.py β€” No Path Exists
$ Input: n = 3, edges = [[0,1,2]], s = 0, marked = [2]
β€Ί Output: -1
πŸ’‘ Note: There is no path from node 0 to node 2, so we return -1.
example_3.py β€” Source is Marked
$ Input: n = 4, edges = [[0,1,5],[1,2,3]], s = 0, marked = [0,2]
β€Ί Output: 0
πŸ’‘ Note: The source node 0 is itself marked, so the minimum distance is 0.

Visualization

Tap to expand
STARTβ›½β›½πŸͺDistance: 5Distance: 8FOUND! Stop hereNot exploredExplorationwavefront
Understanding the Visualization
1
Mark Destinations
Identify all possible destinations (marked nodes) in a set for quick lookup
2
Start Exploration
Begin Dijkstra's algorithm from source, exploring closest nodes first
3
Early Termination
Stop immediately when any marked destination is reached - it's guaranteed to be the closest
Key Takeaway
🎯 Key Insight: Dijkstra's algorithm explores nodes in order of increasing distance from the source, so the first marked destination encountered is guaranteed to be the globally closest one!

Time & Space Complexity

Time Complexity
⏱️
O((E + V) log V)

Single Dijkstra's algorithm with early termination - same as standard shortest path

n
2n
⚑ Linearithmic
Space Complexity
O(V + E)

Space for adjacency list, priority queue, distance array, and marked set

n
2n
βœ“ Linear Space

Constraints

  • 2 ≀ n ≀ 500
  • 1 ≀ edges.length ≀ 104
  • edges[i].length == 3
  • 0 ≀ ui, vi ≀ n-1
  • 1 ≀ wi ≀ 100
  • 1 ≀ marked.length ≀ n
  • All marked nodes are distinct
  • 0 ≀ s ≀ n-1
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 24 Apple 18
68.9K Views
High Frequency
~18 min Avg. Time
1.8K 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