You start at index 0, and your goal is to reach index n - 1.
From any index i, you may perform one of the following operations:
Adjacent Step: Jump to index i + 1 or i - 1, if the index is within bounds.
Prime Teleportation: If nums[i] is a prime numberp, you may instantly jump to any index j != i such that nums[j] % p == 0.
Return the minimum number of jumps required to reach index n - 1.
Β
Example 1:
Input:nums = [1,2,4,6]
Output:2
Explanation:
One optimal sequence of jumps is:
Start at index i = 0. Take an adjacent step to index 1.
At index i = 1, nums[1] = 2 is a prime number. Therefore, we teleport to index i = 3 as nums[3] = 6 is divisible by 2.
Thus, the answer is 2.
Example 2:
Input:nums = [2,3,4,7,9]
Output:2
Explanation:
One optimal sequence of jumps is:
Start at index i = 0. Take an adjacent step to index i = 1.
At index i = 1, nums[1] = 3 is a prime number. Therefore, we teleport to index i = 4 since nums[4] = 9 is divisible by 3.
Thus, the answer is 2.
Example 3:
Input:nums = [4,6,5,8]
Output:3
Explanation:
Since no teleportation is possible, we move through 0 β 1 β 2 β 3. Thus, the answer is 3.
Β
Constraints:
1 <= n == nums.length <= 105
1 <= nums[i] <= 106
Solutions
Solution 1: Preprocessing + BFS
First, we preprocess the list of prime factors for every number up to \(10^6\) and store them in \(\textit{factors}\).
Then we build a graph \(g\). For each index \(i\) and each \(p \in \textit{factors}[nums[i]]\), we add \(i\) to \(g[p]\). In this way, we obtain the list of indices that can be reached by teleportation through each prime number \(p\).
Next, we use breadth-first search to find the minimum number of jumps. We maintain a queue \(q\) to store the indices that can currently be reached, with only index \(0\) in \(q\) initially. Each time we pop an index \(i\) from \(q\), if \(i\) is the target index \(n - 1\), we return the current number of jumps. Otherwise, we add all indices in \(g[nums[i]]\) to \(q\) and remove them from \(g[nums[i]]\) to avoid repeated visits. At the same time, we also add the adjacent indices \(i + 1\) and \(i - 1\) to \(q\) if they are within bounds.
The time complexity is \(O(n \log M)\), and the space complexity is \(O(n \log M)\), where \(n\) is the length of the array, and \(M\) is the maximum value in the array.