Digit Operations to Make Two Integers Equal Problem
Description
LeetCode Problem 3377.
You are given two integers n and m that consist of the same number of digits.
You can perform the following operations any number of times:
- Choose any digit from
nthat is not 9 and increase it by 1. - Choose any digit from
nthat is not 0 and decrease it by 1.
The integer n must not be a prime number at any point, including its original value and after each operation.
The cost of a transformation is the sum of all values that n takes throughout the operations performed.
Return the minimum cost to transform n into m. If it is impossible, return -1.
Example 1:
Input: n = 10, m = 12
Output: 85
Explanation:
We perform the following operations:
- Increase the first digit, now n = 20.
- Increase the second digit, now n = 21.
- Increase the second digit, now n = 22.
- Decrease the first digit, now n = 12.
Example 2:
Input: n = 4, m = 8
Output: -1
Explanation:
It is impossible to make n equal to m.
Example 3:
Input: n = 6, m = 2
Output: -1
Explanation:
Since 2 is already a prime, we can't make n equal to m.
Constraints:
1 <= n, m < 10^4nandmconsist of the same number of digits.
Solution
Approach: Dijkstra + Sieve
Treat every non-prime number with the same digit count as a node. Two numbers are joined by an edge when they differ by one in a single digit (a digit may not go below 0 or above 9, and the leading digit may not become 0). Moving to a number costs that number's value, and the start value n is counted too, so the path cost is the sum of all values visited.
Build a prime sieve up to 10^5. If n or m is prime the answer is -1. Otherwise run Dijkstra from n, keyed by the total cost so far, never entering a prime. The first time we pop m its cost is the answer; if the queue empties first, return -1.
Complexity: with d digits there are at most 10^d nodes and each has at most 2d neighbours, so time is O(10^d * d * log 10^d) and space O(10^d).
import heapq
class Solution:
def __init__(self):
self.sieve = []
def run_sieve(self):
self.sieve = [True] * 100000
self.sieve[0], self.sieve[1] = False, False
for i in range(2, 100000):
if self.sieve[i]:
for j in range(2 * i, 100000, i):
self.sieve[j] = False
def solve(self, n, m):
pq = []
heapq.heappush(pq, (n, n))
visited = set()
while pq:
sum_, cur = heapq.heappop(pq)
if cur in visited:
continue
visited.add(cur)
if cur == m:
return sum_
s = list(str(cur))
for i in range(len(s)):
c = s[i]
if s[i] < '9':
s[i] = chr(ord(s[i]) + 1)
next_ = int(''.join(s))
if not self.sieve[next_] and next_ not in visited:
heapq.heappush(pq, (sum_ + next_, next_))
s[i] = c
if s[i] > '0' and not (i == 0 and s[i] == '1'):
s[i] = chr(ord(s[i]) - 1)
next_ = int(''.join(s))
if not self.sieve[next_] and next_ not in visited:
heapq.heappush(pq, (sum_ + next_, next_))
s[i] = c
return -1
def minOperations(self, n, m):
self.run_sieve()
if self.sieve[n] or self.sieve[m]:
return -1
return self.solve(n, m)