Minimum Multiplications to Reach End

medium

Given an array arr of multipliers, a start number, and an end number, in each step you may replace the current number cur by (cur * arr[i]) % 100000 for any i. Return the minimum number of steps to transform start into end, or -1 if it's impossible.

Hints

Because of the % 100000, only 100000 values are possible — a finite graph.
Multiplying by an arr value is a single step (unit-weight edge).
BFS from start gives the minimum number of multiplications to reach end.

Common doubts

Every edge costs exactly one step, so BFS already visits states in step order; Dijkstra's heap adds a log factor for no benefit.
The modulus caps the reachable values at 100000, so BFS terminates even though multiplication is unbounded in principle.
When end lies in no residue reachable from start via the given multipliers.

Interview follow-ups

Same BFS; the state-space size is just the new modulus.
Then it's a weighted shortest path — use Dijkstra with actual weights.

Fun facts

  • This is a classic 'implicit graph' problem — the graph is defined by a rule, not an edge list.
  • The same modular-state BFS solves lock-combination and number-transformation puzzles.

Asked at

AmazonGoogle
Frequently Sometimes Occasionally
Example 1
Input: arr = [2, 5, 7], start = 3, end = 30
Output: 2
3 → 6 (×2) → 30 (×5).
Example 2
Input: arr = [2], start = 1, end = 3
Output: -1
Powers of two never reach 3.
Constraints

- 1 <= arr.length <= 10^4 - 1 <= arr[i] < 100000 - 0 <= start, end < 100000

Solve this problem →