Taro Logo

Minimum Jumps to Reach End via Prime Teleportation

#2 Most AskedMedium
0 views
Topics:
ArraysGraphsDynamic Programming

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 + 1 or i - 1, if the index is within bounds.
  • Prime Teleportation: If 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:

  • 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

Solution


Clarifying Questions

When 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:

  1. What is the expected range of the array size and the integer values within the array?
  2. How should we handle numbers in the array that are not prime? Can we still jump to adjacent positions from them, but just not use them for teleportation?
  3. What should be returned if it is impossible to reach the end of the array?
  4. Can the array contain negative numbers, zeros, or composite numbers, and how should those be treated?
  5. If multiple identical prime numbers appear across the array, does teleporting to one of them count as a single jump regardless of the distance traveled?

Brute Force Solution

Approach

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:

  1. Begin at the starting position with a jump counter set to zero.
  2. Look at your current position's value and check every possible number that is prime and smaller than your current value.
  3. For each of those prime numbers, if you can subtract it from your current position, consider that as a possible teleportation destination.
  4. Also consider simply taking a normal step forward to the very next position.
  5. From each new position you land on, repeat the entire process by exploring all possible prime teleportations and normal steps from there.
  6. Keep track of every single path that successfully reaches the final destination.
  7. Compare all the successful paths you found and pick the one that used the fewest total jumps.

Code Implementation

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 -1

Big(O) Analysis

Time Complexity
O(n * π(MAX)) – To find the minimum jumps, we perform a breadth-first search across an array of size n. At each position up to n, we generate all prime numbers smaller than the current value to determine valid teleportation destinations. The cost at each position is driven by finding these primes up to the maximum possible value, represented as π(MAX), combined with checking the normal step forward. This results in approximately n multiplied by the number of primes up to MAX operations, which simplifies to O(n * π(MAX)).
Space Complexity
O(N) – To find the shortest path as described in the plain English explanation, the algorithm uses a visited array of size N to keep track of reached positions and prevent redundant processing. It also utilizes a Breadth-First Search queue that can hold up to N elements at most during the exploration of positions. Additionally, a helper structure to generate primes up to the maximum value of N contributes extra memory. Combining these structures, the auxiliary space scales linearly with the input size N, leading to a final Big O notation of O(N).

Optimal Solution

Approach

To 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:

  1. Begin your journey at the starting position and treat this as your first checkpoint.
  2. Look at your current position to see which numbers are prime, as landing on a prime number gives you the magical ability to instantly teleport to any other position marked with that exact same prime number.
  3. Identify all the new spots you can reach from your current location, including both stepping to the immediate next positions and teleporting through any prime numbers you are currently standing on.
  4. Group these newly discovered spots into a new wave of reachable locations, making sure you never revisit a spot you have already explored to keep things efficient.
  5. Count this entire wave of newly reached locations as a single step or jump taken from your starting point.
  6. Repeat the process of looking outward from this new wave, expanding your reach step by step.
  7. The moment your expanding waves touch or include the final destination, stop and report the total number of jumps it took to get there.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n + M log log M) – The time complexity is driven by two main phases: precomputing all prime numbers up to the maximum array value n using the Sieve of Eratosthenes, which takes O(M log log M) time where M is the maximum value, and exploring the graph layer by layer using Breadth-First Search. During the BFS, each of the n positions and each distinct prime factor is visited at most once, meaning queue operations and teleportation lookups scale linearly with n. Combining the prime sieve generation and the linear graph traversal yields a total cost approximating O(n + M log log M), which simplifies to O(n + M log log M).
Space Complexity
O(N + V) – The space complexity is driven by three main data structures: a boolean array to store precomputed prime numbers up to the maximum value V in the input, a visited array of size N to ensure we never revisit a spot, and a queue for layer-by-layer exploration that can hold up to N elements. As the input size N and maximum value V grow, these auxiliary arrays and tracking structures consume memory linearly relative to N and V. Simplifying this, the total extra memory approximates O(N + V).

Edge Cases

Empty or single-element array
How to Handle:
Return zero jumps immediately since we are already at the destination.
Array with no valid path to the end
How to Handle:
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
How to Handle:
Filter or ignore values that yield no prime factors during graph construction to prevent invalid teleportations.
All elements containing the exact same prime number
How to Handle:
Ensure the breadth-first search visits all indices in a single teleport step or limits redundant expansions.
Massive inputs with millions of elements
How to Handle:
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
How to Handle:
Mark entire prime numbers as visited once processed to avoid redundant queue insertions and memory explosion.
Large integer values in the array
How to Handle:
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
How to Handle:
Check the array bounds before running the traversal and return zero jumps.
0/8 completed