Digit Operations to Make Two Integers Equal - Problem
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.
Important constraint: 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.
Input & Output
Example 1 — Basic Transformation
$
Input:
n = 10, m = 12
›
Output:
42
💡 Note:
Path: 10 → 20 → 12. Cost = 10 + 20 + 12 = 42. We avoid 11 because it's prime.
Example 2 — Same Number
$
Input:
n = 34, m = 34
›
Output:
34
💡 Note:
Numbers are already equal, so the cost is just the starting number 34.
Example 3 — Impossible Case
$
Input:
n = 23, m = 56
›
Output:
-1
💡 Note:
Starting number 23 is prime, so no transformations are allowed. Return -1.
Constraints
- 1 ≤ n, m ≤ 104
- n and m have the same number of digits
- n and m are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two numbers n=10 and m=12 with same digit count
2
Transform
Change digits by ±1, avoid primes like 11
3
Output
Minimum cost path: 10→20→12 = 42
Key Takeaway
🎯 Key Insight: Model as shortest path problem where prime numbers are forbidden nodes
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code