Collapse a Sequence to Ones Using Neighbor GCD Replacements
Math & Bit ManipulationAuto-graded · 26 test casesLast 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) <= 501 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split into three cases.
-
The list already has at least one 1. A 1 next to any value
xcan turnxintogcd(1, x) = 1in one move, so ones spread outward. Each non-1 entry needs exactly one move, givingn - (number of ones). -
No ones, but some contiguous window has GCD 1. Let
Lbe the length of the shortest such window. Walking left to right inside it and replacing each next entry with the GCD of the pair makes the last entry equal to the window's GCD, which is 1, afterL - 1moves. Then spread that 1 to the othern - 1entries. Total:(L - 1) + (n - 1). -
The GCD of the entire list is greater than 1. Every value ever produced is a multiple of that GCD, so a 1 can never appear. Return
-1.
Why it is optimal
- Lower bound with ones present: each move changes one entry, and every non-1 entry must change at least once, so at least
n - onesmoves are needed. - Every entry is always the GCD of a contiguous block of the original list. A move combines two blocks that contain adjacent indices, so their union is still contiguous, and the new value is the GCD of that union.
- Creating the first 1: it must come from a contiguous block with GCD 1, which has length at least
L. Information crosses the boundary between positionsiandi+1only through a move on that pair, and a block of lengthLspansL - 1boundaries, so at leastL - 1moves happen before any 1 exists. At that moment the othern - 1entries are not 1, and each still needs a move. The total lower bound matches the construction above.
Finding the shortest window
For every start i, extend the end j rightwards while maintaining a running GCD. The running GCD never grows as the window extends, so the first j with GCD 1 is the shortest window for that start; stop there. Keep the minimum of j - i, which equals L - 1.
Complexity
- Time:
O(n^2 log M)withM <= 10^6, trivial forn <= 50. - Space:
O(1)extra.
Reference solution
from math import gcd
from typing import List
def min_moves_to_all_ones(values: List[int]) -> int:
n = len(values)
# Existing ones each spread to a neighbor in one move.
ones = values.count(1)
if ones:
return n - ones
# Shortest window with GCD 1; store (length - 1).
best = None
for i in range(n):
g = values[i]
for j in range(i + 1, n):
g = gcd(g, values[j])
if g == 1:
if best is None or j - i < best:
best = j - i
break
if best is None:
return -1
return best + n - 1