Minimum Jumps to Reach End via Prime Teleportation Problem
Description
LeetCode Problem 3629.
You are given an integer array nums of length n.
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 + 1ori - 1, if the index is within bounds. - Prime Teleportation: If
nums[i]is a prime numberp, you may instantly jump to any indexj != isuch thatnums[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 <= 10^51 <= nums[i] <= 10^6
Solution
Approach: Preprocessing + BFS
Precompute the prime factors of every number up to 10^6 with a sieve. Then, for each prime p, build the list g[p] of indices whose value is divisible by p. Teleporting from an index with prime value p goes to any index in g[p].
Run a breadth-first search from index 0. From index i the neighbours are i + 1, i - 1 and everything in g[nums[i]]. After using the list g[nums[i]] once we clear it, because every index in it has just been reached and will never need to be revisited. The BFS level in which index n - 1 first appears is the answer.
Complexity: O(n log M) time and space, where n is the length of the array and M is its maximum value (plus the one-off sieve up to 10^6).
from collections import defaultdict
mx = 10**6 + 1
factors = [[] for _ in range(mx)]
for i in range(2, mx):
if not factors[i]:
for j in range(i, mx, i):
factors[j].append(i)
class Solution:
def minJumps(self, nums: List[int]) -> int:
n = len(nums)
g = defaultdict(list)
for i, x in enumerate(nums):
for p in factors[x]:
g[p].append(i)
ans = 0
vis = [False] * n
vis[0] = True
q = [0]
while 1:
nq = []
for i in q:
if i == n - 1:
return ans
idx = g[nums[i]]
idx.append(i + 1)
if i:
idx.append(i - 1)
for j in idx:
if not vis[j]:
vis[j] = True
nq.append(j)
idx.clear()
q = nq
ans += 1