Find Shortest Path with K Hops — LeetCode 2714 Python Solution

HardLeetCode PremiumGraphShortest PathHeap (Priority Queue)
Problem
#2714
Reading time
4 min

The 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.

Example

Input
n = 4, edges = [[0,1,4],[0,2,2],[2,3,6]], s = 1, d = 3, k = 2
Output
2
Explanation
In this example there is only one path from node 1 (the green node) to node 3 (the red node), which is (1->0->2->3) and the length of it is 4 + 2 + 6 = 12. Now we can make weight of two edges 0, we make weight of the blue edges 0, then we have 0 + 2 + 0 = 2. It can be shown that 2 is the minimum length of a path we can achieve with the given condition.

Python solution

Python
class Solution:
    def shortestPathWithHops(
        self, n: int, edges: List[List[int]], s: int, d: int, k: int
    ) -> int:
        g = [[] for _ in range(n)]
        for u, v, w in edges:
            g[u].append((v, w))
            g[v].append((u, w))
        dist = [[inf] * (k + 1) for _ in range(n)]
        dist[s][0] = 0
        pq = [(0, s, 0)]
        while pq:
            dis, u, t = heappop(pq)
            for v, w in g[u]:
                if t + 1 <= k and dist[v][t + 1] > dis:
                    dist[v][t + 1] = dis
                    heappush(pq, (dis, v, t + 1))
                if dist[v][t] > dis + w:
                    dist[v][t] = dis + w
                    heappush(pq, (dis + w, v, t))
        return int(min(dist[d]))

Complexity

MeasureComplexity
TimeO(n^2 \times \log n)
SpaceO(n \times k), where n represents the number of nodes and k represents the maximum number of edges crossed auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2714. Find Shortest Path with K Hops is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2714. Find Shortest Path with K Hops?
LeetCode 2714. Find Shortest Path with K Hops is rated Hard on LeetCode.
What is the time complexity of LeetCode 2714. Find Shortest Path with K Hops?
The Python solution on this page runs in O(n^2 \times \log n).
What is the space complexity of LeetCode 2714. Find Shortest Path with K Hops?
The Python solution on this page uses O(n \times k), where n represents the number of nodes and k represents the maximum number of edges crossed auxiliary space.
What topics does LeetCode 2714. Find Shortest Path with K Hops cover?
LeetCode 2714. Find Shortest Path with K Hops is tagged Graph, Shortest Path and Heap (Priority Queue) on LeetCode.
Is LeetCode 2714. Find Shortest Path with K Hops a premium problem?
Yes. LeetCode 2714. Find Shortest Path with K Hops is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview