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 n that is not 9 and increase it by 1.
  • Choose any digit from n that 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
Transform 10 → 12 (Avoiding Prime Numbers)Start10n = 10Prime11Blocked ✗Valid20Cost +20Target12m = 12+1+10 to first digit+2Operations: +1 or -1 to any digit (not creating 0 or 9)Constraint: Never create a prime numberMinimum Cost Path: 10 + 20 + 12 = 42Use Dijkstra's algorithm to find shortest path in digit space
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
Asked in
Google 15 Meta 12 Amazon 8
8.8K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen