Problem solution · Python

Shortest Path with at Most K Consecutive Identical Characters

Shortest Path with at Most K Consecutive Identical Characters: a Python solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Heap or priority queue
Source
Kamyu LeetCode Solutions
Length
36 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Shortest Path with at Most K Consecutive Identical Characters, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 36 lines of Python from the credited upstream file shortest-path-with-at-most-k-consecutive-identical-characters.py.
  • The implementation visibly relies on sequence storage, work queue.
  • No explicit loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeShortest Path with at Most K Consecutive Identical Characters · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(e * k * log(n * k))# Space: O(n * k + e) import heapq  # dijkstra's algorithmsclass Solution(object):    def shortestPath(self, n, edges, labels, k):        """        :type n: int        :type edges: List[List[int]]        :type labels: str        :type k: int        :rtype: int        """        adj = [[] for _ in xrange(n)]        for u, v, w in edges:            adj[u].append((v, w))        dist = [[float("inf")]*k for _ in xrange(n)]        dist[0][0] = 0        min_heap = [(dist[0][0], 0, 0)]        while min_heap:            d, u, c = heapq.heappop(min_heap)            if d > dist[u][c]:                continue            if u == n-1:                return d            for v, w in adj[u]:                nc = c+1 if labels[v] == labels[u] else 0                if not (nc < k and d+w < dist[v][nc]):                    continue                dist[v][nc] = d+w                heapq.heappush(min_heap, (dist[v][nc], v, nc))        return -1 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗