Digit Operations to Make Two Integers Equal - Problem

Imagine you're playing a number transformation game where you need to turn one number into another by incrementing or decrementing individual digits, but there's a catch - your number can never become prime!

Given two integers n and m with the same number of digits, you can perform these operations on n:

  • πŸ”Ό Increment: Choose any digit that's not 9 and increase it by 1
  • πŸ”½ Decrement: Choose any digit that's not 0 and decrease it by 1

Critical Rule: The number n must never be prime at any point during the transformation process (including its original value).

The cost of transformation is the sum of all intermediate values that n takes during the operations. Your goal is to find the minimum cost to transform n into m.

Return -1 if the transformation is impossible.

Input & Output

example_1.py β€” Basic Transformation
$ Input: n = 10, m = 12
β€Ί Output: 85
πŸ’‘ Note: Transform 10 β†’ 11 β†’ 12. Cost = 10 + 11 + 12 = 33. But we need to avoid primes: 10 β†’ 20 β†’ 21 β†’ 22 β†’ 12 might be one valid path with higher cost of 85.
example_2.py β€” Prime Start Invalid
$ Input: n = 17, m = 19
β€Ί Output: -1
πŸ’‘ Note: Since 17 is prime, we cannot start the transformation process. Return -1.
example_3.py β€” Same Numbers
$ Input: n = 48, m = 48
β€Ί Output: 48
πŸ’‘ Note: n and m are the same. Since 48 is not prime, the cost is just n itself = 48.

Constraints

  • 1 ≀ n, m < 104
  • n and m have the same number of digits
  • n must not be prime initially

Visualization

Tap to expand
Number Transformation NetworkSTARTPRIMEPRIMETARGETBLOCKEDValid (Safe) NumbersPrime (Dangerous) NumbersStart/Target PositionsOptimal Path (Minimum Cost)Algorithm: Dijkstra's Shortest Pathβ€’ Each number is a node in the graphβ€’ Edge weight = destination number valueβ€’ Skip prime numbers (invalid states)β€’ Find minimum cost path from start to target
Understanding the Visualization
1
Map the Territory
Identify all valid (non-prime) numbers as safe nodes in our network
2
Find Connections
Each number connects to others by incrementing/decrementing individual digits
3
Calculate Costs
Each step to a new number costs the value of that destination number
4
Navigate Optimally
Use Dijkstra's algorithm to find the cheapest route from start to destination
Key Takeaway
🎯 Key Insight: Transform a number manipulation problem into a graph shortest-path problem by treating valid numbers as nodes and digit operations as weighted edges.
Asked in
Google 28 Amazon 22 Microsoft 15 Meta 12
26.1K Views
Medium Frequency
~35 min Avg. Time
847 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