- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 44 lines of Python from the credited upstream file 3377.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.
Use this to learn the idea, then write your own version.
1class Solution:2 def minOperations(self, n: int, m: int) -> int:3 isPrime = self._sieveEratosthenes(10000)4 if isPrime[n] or isPrime[m]:5 return -16 return self._dijkstra(n, m, isPrime)7 8 def _dijkstra(self, src: int, dst: int, isPrime: list[bool]) -> int:9 seen = {src}10 minHeap = [(src, src)] 11 12 while minHeap:13 cost, curr = heapq.heappop(minHeap)14 if curr == dst:15 return cost16 s = list(str(curr))17 for i, c in enumerate(s):18 if c < '9':19 s[i] = str(int(c) + 1)20 nextNum = int(''.join(s))21 if not isPrime[nextNum] and nextNum not in seen:22 heapq.heappush(minHeap, (cost + nextNum, nextNum))23 seen.add(nextNum)24 s[i] = c25 if c > '0' and not (i == 0 and c == '1'):26 s[i] = str(int(c) - 1)27 nextNum = int(''.join(s))28 if not isPrime[nextNum] and nextNum not in seen:29 heapq.heappush(minHeap, (cost + nextNum, nextNum))30 seen.add(nextNum)31 s[i] = c32 33 return -134 35 def _sieveEratosthenes(self, n: int) -> list[bool]:36 isPrime = [True] * n37 isPrime[0] = False38 isPrime[1] = False39 for i in range(2, int(n**0.5) + 1):40 if isPrime[i]:41 for j in range(i * i, n, i):42 isPrime[j] = False43 return isPrime44