Minimum multiplications to reach end
Pattern: Shortest paths
Every number from 0 to 99999 is a vertex; multiplying by an array value (mod 100000) is an edge. BFS from start counts the fewest multiplications to reach end.
The problem
Starting from start, each step multiplies the current number by any value in arr and takes the result modulo 100000.
Return the fewest steps to reach end, or -1 if it cannot be reached.
Think first
- What are the vertices?
- What does one multiplication do?
- Why does BFS terminate?
Hints
Brute force, and why it fails
Try every sequence of multiplications: exponential.
The key insight
The states are few and every step costs one, so BFS over states finds the minimum.
Dry run
| step | 1 |
|---|
arr [2, 5, 7], start 3, end 30. Step 1: 6, 15, 21.
Step 1 of 3
The plan
dist[start] = 0; BFS: for a in arr: v = u * a mod 100000; if unvisited: dist[v] = dist[u] + 1
Complexity
- Time
O(100000 × len(arr))- Space
O(100000)
Each state at most once.
Edge cases
- start equals end: 0.
- Unreachable: -1.
- end = 0.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int minimumMultiplications(int[] arr, int start, int end) {
final int MOD = 100000;
int[] dist = new int[MOD]; // every number from 0 to 99999 is a vertex
Arrays.fill(dist, -1);
dist[start] = 0;
Queue<Integer> q = new ArrayDeque<>();
q.add(start);
while (!q.isEmpty()) { // each multiplication is one step: BFS
int u = q.poll();
if (u == end) return dist[u];
for (int a : arr) {
int v = (int) ((long) u * a % MOD);
if (dist[v] == -1) { dist[v] = dist[u] + 1; q.add(v); }
}
}
return -1;
}
}C++
class Solution {
public:
int minimumMultiplications(vector<int>& arr, int start, int end) {
const int MOD = 100000;
vector<int> dist(MOD, -1); // every number from 0 to 99999 is a vertex
dist[start] = 0;
queue<int> q;
q.push(start);
while (!q.empty()) { // each multiplication is one step: BFS
int u = q.front();
q.pop();
if (u == end) return dist[u];
for (int a : arr) {
int v = static_cast<int>(static_cast<long long>(u) * a % MOD);
if (dist[v] == -1) { dist[v] = dist[u] + 1; q.push(v); }
}
}
return -1;
}
};Python
from collections import deque
class Solution:
def minimumMultiplications(self, arr: list[int], start: int, end: int) -> int:
MOD = 100000
dist = [-1] * MOD # every number from 0 to 99999 is a vertex
dist[start] = 0
q = deque([start])
while q: # each multiplication is one step: BFS
u = q.popleft()
if u == end:
return dist[u]
for a in arr:
v = u * a % MOD
if dist[v] == -1:
dist[v] = dist[u] + 1
q.append(v)
return -1Common mistakes
- Overflow when multiplying before the modulo.
- Not marking states visited.