Ctrl K

Split by Shared Ends

Medium
You are given an array of positive integers values. Cut it into contiguous non-empty pieces so that every element lands in exactly one piece and the first and last numbers of each piece share a divisor greater than 1. In a one-element piece, that element is both the first and the last. What sits inside a piece does not matter; only its two ends are checked. Return the smallest number of pieces. If no such split exists, return -1.
Example 1
values=[6, 5, 9, 10, 25] → 2

The piece [6, 5, 9] starts with 6 and ends with 9, which share the divisor 3. The piece [10, 25] has ends sharing 5. A single piece fails because 6 and 25 share no divisor above 1.

Example 2
values=[4, 9, 2, 3] → 2

Take [4, 9, 2] (ends 4 and 2, GCD 2) and [3]. One piece is impossible since 4 and 3 share no divisor above 1.

Example 3
values=[8, 1] → -1

The 1 cannot sit in any piece, as its GCD with anything is 1. The answer is -1.

Constraints
  • 1 ≤ len(values) ≤ 1000
  • 1 ≤ values[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsChunks With a Common Divisor MediumBump Numbers to Fit the Divisors HardPrimes Below a Bound MediumNth Number Built From Given Primes MediumChain of Multiples Medium
loading Python…
Input
values=[6, 5, 9, 10, 25]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 177 tests on the server, hidden ones included.