Find Shortest Path with K Hops - Problem

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

You are also given two nodes s and d, and a positive integer k. Your task is to find the shortest path from s to d, but you can hop over at most k edges. In other words, make the weight of at most k edges 0 and then find the shortest path from s to d.

Return the length of the shortest path from s to d with the given condition.

Input & Output

Example 1 — Basic Graph with 2 Free Hops
$ Input: n = 4, edges = [[0,1,10],[0,2,1],[1,2,5],[2,3,1]], s = 0, d = 3, k = 2
Output: 1
💡 Note: Skip edges (0,1) and (1,2), then path 0→2→3 costs 1+1=2, but we can also skip (2,3) and take path 0→2→3 with cost 1+0=1
Example 2 — Linear Chain
$ Input: n = 3, edges = [[0,1,5],[1,2,5]], s = 0, d = 2, k = 1
Output: 5
💡 Note: Skip one edge: either 0→1 (skip) + 1→2 (cost 5) = 5, or 0→1 (cost 5) + 1→2 (skip) = 5
Example 3 — No Hops Available
$ Input: n = 3, edges = [[0,1,2],[1,2,3],[0,2,10]], s = 0, d = 2, k = 0
Output: 5
💡 Note: Cannot skip any edges, shortest path is 0→1→2 with cost 2+3=5

Constraints

  • 2 ≤ n ≤ 1000
  • 1 ≤ edges.length ≤ min(n×(n-1)/2, 2000)
  • edges[i].length == 3
  • 0 ≤ ui, vi ≤ n-1
  • 1 ≤ wi ≤ 106
  • 0 ≤ s, d ≤ n-1
  • s ≠ d
  • 1 ≤ k ≤ n
  • Graph is connected

Visualization

Tap to expand
INPUTWeighted Graph + Parameters012310151Source: 0, Destination: 3Free Hops (k): 2Can skip up to 2 edge weightsALGORITHMModified Dijkstra with State1Initialize Statesdist[0][2] = 0 (start)2Explore OptionsFor each edge: use OR skip3Update Best DistancesTrack min dist[node][hops]4Find Optimal PathReturn when destination reachedPriority Queue States:(dist=0, node=0, hops=2)(dist=0, node=2, hops=1) ← skip edge(dist=0, node=3, hops=0) ← optimal!RESULTOptimal Path FoundMinimum Cost: 1Path: 0 → 2 → 3Strategy: Skip edge (0,2)Actual cost: 0 + 1 = 1Hops used: 1 out of 2Alternative Paths:0→1→2→3: cost = 10+5+1 = 160→2→3 (no skip): cost = 1+1 = 20→2→3 (skip 0→2): cost = 0+1 = 1 ✓Key Insight:Track both current position AND remaining free hops as combined state.This allows optimal decisions: skip expensive edges when beneficial.TutorialsPoint - Find Shortest Path with K Hops | Modified Dijkstra
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 25
28.4K Views
Medium Frequency
~35 min Avg. Time
892 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