07. Minimum Multiplications to reach End
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
By initial intuition, we recognized that this problem could be solved using dynamic programming (DP). However, considering the constraints, we realized that the DP approach would potentially involve a maximum of 1e4 x 1e5
iterations and require a 2D matrix to store intermediate results. Given these constraints, there is a risk of encountering Time Limit Exceeded (TLE) issues. Therefore, we needed to explore a more efficient solution.
Generally, the Breadth-First Search (BFS) approach is typically preferred when searching for the minimum number of steps or levels type questions. Therefore, I used BFS to find the desired answer.
Create a vector dp
of size MOD
to store the minimum number of multiplications needed to reach each state.
Initialize dp[start]
to 0, as we start from start
.
Create a queue to perform BFS and Push start
into the queue.
While the queue is not empty, do the following:
Store and Pop the front element current
from the queue.
For each element arr[i]
in the input array, calculate the next state as (1LL * current * arr[i]) % MOD
.
If dp[next]
is -1 (meaning it's not visited yet), update dp[next]
to dp[current] + 1
and push next
into the queue.
If next
is equal to end
, return dp[next]
as we have reached the desired state.
If the loop completes and we haven't reached end
, return -1, indicating it's not possible to reach end
from start
.
Time Complexity: As we iterate through elements that haven't been visited yet, the maximum number of iterations is limited to MOD
. Therefore, the time complexity of this algorithm is O(MOD)
.
Auxiliary Space Complexity: The auxiliary space complexity is O(MOD)
as we use a dp
array of size MOD to store intermediate results.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.