Minimum Jumps to Reach End via Prime Teleportation

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
Inputnums = [1,2,4,6]
Output2
One optimal sequence is to step from index 0 to index 1, then teleport from prime value 2 to index 3 because 6 is divisible by 2.
Example 2
Inputnums = [2,3,4,7,9]
Output2
One optimal sequence is to step from index 0 to index 1, then teleport from prime value 3 to index 4 because 9 is divisible by 3.

Constraints

  • 1 <= n == nums.length <= 10^5
  • 1 <= nums[i] <= 10^6

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate