Ctrl K

Composite Digit Walk

Medium
A display shows a positive integer start. In one step you may pick any of its digits and raise it by 1 (if it is not 9) or lower it by 1 (if it is not 0). The number of digits never changes: the leading digit may not become zero. The display breaks if it ever shows a prime number, so neither the starting number, nor any intermediate one, nor the final one may be prime. The cost of a walk is the sum of every number the display has shown, including start and the final number. Find the minimum cost of getting target onto the display, or return -1 if it cannot be done.
Example 1
start=20, target=24 → 186

Going straight through 23 is not allowed, since it is prime. The cheapest detour goes through the thirties: 20 → 21 → 22 → 32 → 33 → 34 → 24, costing 20 + 21 + 22 + 32 + 33 + 34 + 24 = 186.

Example 2
start=14, target=16 → 45

14 → 15 → 16, all three are composite: 14 + 15 + 16 = 45.

Example 3
start=9, target=7 → -1

7 is prime, so the counter may never show it and the answer is -1.

Constraints
  • 1 ≤ start, target < 10⁵
  • start and target have the same number of digits
  • 1 is not considered prime
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShortest Path of a Rolling Ball MediumBroadcast Reach Time MediumCheapest Trip With Few Layovers MediumMost Reliable Relay Route MediumRoutes That Keep Getting Closer Medium
loading Python…
Input
start=20, target=24
Expected
186

Run checks the first 3 tests in your browser. Submit checks all 112 tests on the server, hidden ones included.