This problem can be modeled as an unweighted graph where each number from 0
to 99999
is a node. An edge exists between u
and v
if v = (u * x) % 100000
for some x
in the array arr
.
To find the shortest path (minimum number of multiplications) from start
to end
, we can use the Breadth-First Search (BFS) algorithm. BFS guarantees that we reach the target node using the minimum number of steps because it explores all nodes level by level.
We maintain a queue
for BFS and a visited
array of size 100000
to track which numbers we have already seen. For each number dequeued, we try all possible multiplications using elements of arr
, compute the result modulo 100000
, and enqueue it if it hasn't been visited yet.
If we reach end
, we return the number of steps taken. If we exhaust the queue without reaching end
, we return -1
.