KatInterview

Collapse a Sequence to Ones Using Neighbor GCD Replacements

Math & Bit ManipulationAuto-graded · 26 test cases
MediumAuto-gradedMath & Bit Manipulationgcdsubarraynumber-theory

Last updated

Find the minimum number of neighbor-GCD replacements to turn an entire array into ones, using shortest coprime-window search and a lower-bound argument.

You have a list values of positive integers. A single move works like this: pick a position i such that 0 <= i < len(values) - 1, compute the greatest common divisor of values[i] and values[i + 1], and write that result into exactly one of those two positions (your choice), leaving the other position unchanged.

Return the smallest number of moves that makes every entry of values equal to 1. If no sequence of moves can achieve this, return -1.

Notes

  • The greatest common divisor of two positive integers is the largest positive integer dividing both. For instance, the GCD of 12 and 18 is 6, and the GCD of 4 and 9 is 1.
  • Moves happen one after another, and each move uses the current contents of the list, including the effects of earlier moves.
  • If the list already consists only of ones, the answer is 0.

Constraints

  • 2 <= len(values) <= 50
  • 1 <= values[i] <= 10^6

Examples

Example 1

Input: min_moves_to_all_ones([6, 10, 15])

Output: 4

Example 2

Input: min_moves_to_all_ones([3, 1, 9, 1])

Output: 2

Example 3

Input: min_moves_to_all_ones([4, 6, 8])

Output: -1

Hints

Hint 1

Each move rewrites exactly one entry, so every entry that is not 1 needs at least one move. What does that imply when the list already contains some ones?

Hint 2

If there are no ones, you must first manufacture one. Every value in the list is always the GCD of some contiguous block of the original list, so look for the shortest contiguous block whose GCD is 1.

Hint 3

A block of length L costs L - 1 moves to produce its first 1, after which that 1 can be pushed to each of the other n - 1 entries at one move apiece. If the whole list has GCD greater than 1, a 1 can never appear.