#3377
Digit Operations to Make Two Integers Equal
MediumMathGraph TheoryHeap (Priority Queue)Number TheoryShortest PathGraph TraversalDijkstra's Algorithm
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can model the problem as a graph where each node represents a number and edges represent valid transformations. Using a shortest path algorithm, we can efficiently find the minimum cost to transform n to m.
⚙️
Algorithm
3 steps- 1Step 1: Create a priority queue to explore numbers starting from n.
- 2Step 2: For each number, generate valid transformations and push them into the queue if they are not prime.
- 3Step 3: Continue until m is reached or all possibilities are exhausted, tracking the total cost.
solution.py22 lines
1import heapq
2
3def minCost(n, m):
4 def is_prime(x):
5 if x < 2: return False
6 for i in range(2, int(x**0.5) + 1):
7 if x % i == 0: return False
8 return True
9 pq = [(n, n)]
10 visited = set()
11 while pq:
12 cost, num = heapq.heappop(pq)
13 if num == m: return cost
14 if num in visited or is_prime(num): continue
15 visited.add(num)
16 for i in range(len(str(num))):
17 digit = (num // (10**i)) % 10
18 if digit < 9:
19 heapq.heappush(pq, (cost + num + 1, num + 10**i))
20 if digit > 0:
21 heapq.heappush(pq, (cost + num + 1, num - 10**i))
22 return -1ℹ
Complexity note: The complexity is driven by the number of transformations and the priority queue operations, which are efficient for this problem.
- 1Transformations must avoid prime numbers.
- 2Each digit can be incremented or decremented independently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.