Problem Description
Given two integers n and m having the same number of digits, you may change any one digit of n at a time by either increasing it by 1 (if it is not 9) or decreasing it by 1 (if it is not 0). However, at every step (including the original n and at every intermediate result) the current integer must not be a prime number. The goal is to convert n to m with a sequence of these digit operations such that the transformation cost––which is defined as the sum of all the integer values that n takes (including the starting value and after each operation)––is minimized. Return the minimum cost if possible, otherwise return -1.
Key Insights
- Model the problem as a weighted graph with nodes representing valid integers (with the given number of digits and not prime) and edges representing a single allowed digit operation.
- The weight of an edge from one integer to its neighbor is the neighbor’s integer value (and the starting integer is also charged).
- Use Dijkstra’s algorithm in order to find the minimum cost path from n to m.
- Pre-compute all primes up to 10^4 (the maximum possible value) so that each generated neighbor can be quickly validated.
- Ensure that digit operations do not produce numbers with a different number of digits (avoid producing a leading zero).
Space and Time Complexity
Time Complexity: O(N * D) where N is the number of states (roughly up to 9 * 10^(d-1) for numbers with d digits, d ≤ 4) and D is the number of digits. This is acceptable given the constraints. Space Complexity: O(N) for storing the cost for each valid state and the prime-check table.
Solution
We use Dijkstra’s algorithm to traverse the state space where each state is a valid integer with the same number of digits as n. Each transition changes one digit by ±1 (ensuring that the most significant digit never becomes 0 and that intermediate states are not prime). The cost accumulated when moving to a neighbor equals the neighbor’s value. The algorithm proceeds by:
- Precomputing a sieve to mark prime numbers up to 10^4.
- Checking that the starting integer (n) and target integer (m) are non-prime.
- Converting the current integer to a string representation so that we can perform digit-level operations.
- For each valid digit operation (increase if digit < 9, decrease if digit > 0 and if it doesn’t result in a leading zero), computing the new integer value and validating that it is non-prime.
- Using a min-heap (priority queue) to always expand the state with the lowest total cost path so far.
- If m is reached, return the total cost; otherwise, if no valid transformation exists, return -1.