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.
Input: arr = [2, 5, 7], start = 3, end = 30 Output: 2 3 → 6 (×2) → 30 (×5).
Input: arr = [2], start = 1, end = 3 Output: -1 Powers of two never reach 3.
- 1 <= arr.length <= 10^4 - 1 <= arr[i] < 100000 - 0 <= start, end < 100000
Every reachable value lives in 0 .. 99999 (because of the % 100000), so this is a graph on 100000 states: from state cur, one step (an edge of weight 1) leads to (cur * arr[i]) % 100000 for each multiplier. "Minimum steps" is then the shortest path from start to end on an unweighted graph — a job for BFS.
BFS from start, generating each state's up-to-|arr| successors and recording the step count when first reached; the first time you pop end, that count is the answer. Since edges are unit-weight, plain BFS is optimal; Dijkstra also works but its heap is unnecessary overhead. O(100000 · |arr|).
“How large is the state space?”
100000 — every value is taken mod 100000.
“If end is unreachable?”
Return -1.
Each number mod 100000 is a node; multiplying by an arr value is a unit-weight edge, so I BFS from start.
The step count when I first reach end is the minimum; if BFS never reaches it, return -1.
Worked example — arr = [2, 5, 7], start = 3, end = 30
3 --*2--> 6 --*5--> 30 (2 steps) answer = 2
Only 100000 possible values.
So BFS gives the fewest steps.
BFS settles states in step order.
| Dijkstra | BFS | |
|---|---|---|
| Structure | min-heap by steps | plain queue |
| Time | O(S·|arr|·log S) | O(S·|arr|) |
| Note | heap is unnecessary | optimal for unit weights |
Both return the same minimum step count; BFS is the natural fit. Full code is in the Approaches selector below.
Key takeaway
The % 100000 makes a finite 100000-state graph; multiplying is a unit-weight edge. BFS from start gives the minimum steps to end, or -1. O(100000·|arr|).
BFS from start; neighbour = (cur * m) % 100000; first reach of end = answer