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
Digit Operations: Transform n to m INPUT n = 10 m = 12 State Graph (partial) 10 20 00 21 12 Constraint: n must NEVER be prime during operations ALGORITHM STEPS 1 Build State Graph Nodes = non-prime numbers Edges = digit +1 or -1 2 Run Dijkstra Start: n=10, Target: m=12 Cost = sum of visited values 3 Priority Queue Min-heap by total cost Process lowest cost first 4 Track Path 10 --> 20 --> 21 --> 12 Optimal Path Found: 10 --> 20 --> 12 Cost: 10 + 20 + 12 = 42 (All intermediate values are non-prime) FINAL RESULT Minimum Cost 42 Transformation Path: 10 | 20 | 12 OK - Path Valid! No primes encountered Output: 42 Key Insight: Dijkstra's algorithm finds shortest path where edge weight = destination node value. Pre-compute prime numbers using Sieve of Eratosthenes. Only traverse through non-prime states. Total cost = sum of all visited states. Return -1 if target unreachable through non-primes only. TutorialsPoint - Digit Operations to Make Two Integers Equal | Dijkstra's Algorithm
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