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:
i + 1 or i - 1, if the index is within bounds.nums[i] is a prime number p, 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:
i = 0. Take an adjacent step to index 1.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:
i = 0. Take an adjacent step to index i = 1.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:
0 → 1 → 2 → 3. Thus, the answer is 3.Constraints:
1 <= n == nums.length <= 1051 <= nums[i] <= 106When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are standing at the starting position and want to find your way to the final destination using teleportation or normal steps. The brute force approach involves exploring every single possible sequence of movements, keeping track of how many jumps it takes each time, until you find the shortest path.
Here's how the algorithm would work step-by-step:
def min_jumps_prime_teleportation(positions_array): # We must precompute primes up to the max value to efficiently find valid teleport targets max_position_value = max(positions_array) is_prime_flags = [True] * (max_position_value + 1) is_prime_flags[0] = is_prime_flags[1] = False current_number = 2 while current_number * current_number <= max_position_value: if is_prime_flags[current_number]: for multiple in range(current_number * current_number, max_position_value + 1, current_number): is_prime_flags[multiple] = False current_number += 1 # Breadth-first search queue stores tuples of current index and jump count to ensure shortest path from collections import deque traversal_queue = deque([(0, 0)]) visited_indices = {0} last_index = len(positions_array) - 1 while traversal_queue: current_index, jump_count = traversal_queue.popleft() if current_index == last_index: return jump_count # Teleportation moves allow jumping backward by any prime factor or value present at the index current_value = positions_array[current_index] for candidate_prime in range(2, current_value + 1): if is_prime_flags[candidate_prime]: target_index = current_index - candidate_prime if target_index >= 0 and target_index not in visited_indices: visited_indices.add(target_index) traversal_queue.append((target_index, jump_count + 1)) # Normal step forward allows moving to the immediately adjacent next position next_index = current_index + 1 if next_index <= last_index and next_index not in visited_indices: visited_indices.add(next_index) traversal_queue.append((next_index, jump_count + 1)) return -1To find the fewest jumps to reach the final destination, we can think of the journey as a web of connected stepping stones where prime numbers offer special teleportation powers. Instead of blindly guessing every path, we use a smart exploration strategy that checks all reachable spots layer by layer until we land on the finish line.
Here's how the algorithm would work step-by-step:
def min_jumps(array_elements):
total_elements = len(array_elements)
if total_elements <= 1:
return 0
maximum_value = max(array_elements)
sieve_limit = max(maximum_value + 1, 2)
is_prime = [True] * sieve_limit
is_prime[0] = is_prime[1] = False
for current_number in range(2, int(sieve_limit ** 0.5) + 1):
if is_prime[current_number]:
for multiple in range(current_number * current_number, sieve_limit, current_number):
is_prime[multiple] = False
# Precompute positions for each prime to enable instant O(1) teleportation jumps across the array.
prime_to_indices = {}
for index, value in enumerate(array_elements):
if is_prime[value]:
if value not in prime_to_indices:
prime_to_indices[value] = []
prime_to_indices[value].append(index)
visited_indices = [False] * total_elements
visited_primes = [False] * sieve_limit
current_wave = [0]
visited_indices[0] = True
jump_count = 0
while current_wave:
if total_elements - 1 in current_wave:
return jump_count
next_wave = []
for current_position in current_wave:
current_value = array_elements[current_position]
if is_prime[current_value] and not visited_primes[current_value]:
visited_primes[current_value] = True
for teleport_target in prime_to_indices[current_value]:
if not visited_indices[teleport_target]:
visited_indices[teleport_target] = True
next_wave.append(teleport_target)
for candidate_position in (current_position - 1, current_position + 1):
if 0 <= candidate_position < total_elements and not visited_indices[candidate_position]:
visited_indices[candidate_position] = True
next_wave.append(candidate_position)
# Transition to the next wave ensures we explore the graph level by level for shortest path.
current_wave = next_wave
jump_count += 1
return -1| Case | How to Handle |
|---|---|
| Empty or single-element array | Return zero jumps immediately since we are already at the destination. |
| Array with no valid path to the end | Return negative one or a sentinel value if the queue empties before reaching the final index. |
| Numbers with no prime factors or non-positive numbers | Filter or ignore values that yield no prime factors during graph construction to prevent invalid teleportations. |
| All elements containing the exact same prime number | Ensure the breadth-first search visits all indices in a single teleport step or limits redundant expansions. |
| Massive inputs with millions of elements | Use a linear sieve for prime factorization and an adjacency map to avoid quadratic time complexity during graph building. |
| Repeated prime factors across many indices | Mark entire prime numbers as visited once processed to avoid redundant queue insertions and memory explosion. |
| Large integer values in the array | Precompute primes up to the maximum possible array value using a sieve to ensure efficient O(sqrt(N)) factorization. |
| Already standing at the final index initially | Check the array bounds before running the traversal and return zero jumps. |