BackmediumUncategorized uncategorized medium

Shortest Path via Divisibility Solution

Problem Statement

You are given an integer array `nums` and two integers `start` and `end`, representing 0-indexed positions in `nums`. You can move from index `i` to index `j` (`i != j`) if and only if `nums[i]` is a multiple of `nums[j]`, or `nums[j]` is a multiple of `nums[i]`. Return the minimum number of moves to travel from index `start` to index `end`. If there is no possible path, return `-1`.

Example 1
Input
nums = [5, 15, 3], start = 0, end = 2
Output
2

Explanation: Indices 0 (5) and 1 (15) are connected (15 is multiple of 5). Indices 1 (15) and 2 (3) are connected (15 is multiple of 3). Path: 0 -> 1 -> 2. Total edges: 2.

Constraints

  • 2 <= nums.length <= 1000
  • 1 <= nums[i] <= 10^6
  • 0 <= start, end < nums.length
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free