Minimum Neighbor-GCD Replacements to Reach All Ones
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given an array nums of positive integers, you may repeatedly perform the following neighbor replacement step: select an index i (0 <= i < len(nums) - 1), compute the greatest common divisor g = gcd(nums[i], nums[i + 1]), and overwrite either nums[i] or nums[i + 1] (never both in a single step) with g.
Compute the smallest number of steps required so that every entry in nums becomes 1. If reaching all 1s is impossible regardless of how steps are chosen, return -1.
def min_operations_to_all_ones(nums: list[int]) -> int:
Operation Rules
- Greatest common divisor:
gcd(a, b)denotes the largest positive integer that evenly divides bothaandb(for instance,gcd(14, 21) = 7andgcd(8, 15) = 1). - Sequential updates: Steps execute one after another, so each step reads the current values left behind by all prior replacements.
- Zero-step base case: When every element in
numsis already1,0steps are needed.
Examples
Example 1
Input: nums = [10, 14, 35]
Output: 4
No adjacent pair is initially coprime (gcd(10, 14) = 2 and gcd(14, 35) = 7), so we first combine across the full triple:
1. Overwrite 14 with gcd(10, 14) = 2 -> [10, 2, 35]
2. Overwrite 35 with gcd(2, 35) = 1 -> [10, 2, 1]
3. Overwrite 2 with gcd(2, 1) = 1 -> [10, 1, 1]
4. Overwrite 10 with gcd(10, 1) = 1 -> [1, 1, 1]
Four steps is minimal.
Example 2
Input: nums = [8, 1, 6, 1, 12]
Output: 3
Two entries already equal 1. Replacing 8 via gcd(8, 1) = 1, 6 via gcd(1, 6) = 1, and 12 via gcd(1, 12) = 1 turns the three remaining entries into 1 in 3 steps.
Example 3
Input: nums = [9, 15, 21, 6]
Output: -1
Every integer in nums is divisible by 3. Any GCD formed from multiples of 3 remains a multiple of 3, so 1 can never appear.
Constraints
2 <= len(nums) <= 501 <= nums[i] <= 10^6
Step-by-step walkthrough
Understand the operation and two GCD rules
In each step, we pick two neighboring indices
iandi + 1and overwrite one of them (never both at once!) withgcd(nums[i], nums[i + 1]). Two fundamental properties of greatest common divisors unlock the problem:- Once you have a
1, it spreads in 1 step per neighbor:gcd(1, x) = 1for every positive integerx, so a1sitting beside any valuexconvertsxinto1in one step. - A shared factor across the entire array can never vanish: when every element in
numsis a multiple of somed > 1(such as[9, 15, 21, 6]withd = 3), every GCD ever formed stays divisible byd, making1unreachable (-1).
Example 1: nums = [10, 14, 35] (no adjacent pair has GCD 1!) step 1: gcd(10, 14) = 2 -> overwrite index 1: [10, 2, 35] step 2: gcd(2, 35) = 1 -> overwrite index 2: [10, 2, 1] <-- first 1 created! step 3: gcd(2, 1) = 1 -> overwrite index 1: [10, 1, 1] step 4: gcd(10, 1) = 1 -> overwrite index 0: [1, 1, 1] (4 steps total)- Once you have a
Why breadth-first search is too slow
On tiny inputs (
n <= 4), you can model every reachable array tuple as a graph node, treat each valid neighbor replacement as an edge, and run breadth-first search until reaching[1, 1, ..., 1]. That works well as a randomized test oracle, but the count of distinct reachable array states explodes exponentially withn. Atn = 50, state-space search cannot finish in time — we need a direct mathematical formula.Case 1: at least one `1` is already present
Suppose
numsalready containsones_count >= 1copies of1, leavingn - ones_countentries strictly greater than1.- Why at least
n - ones_countsteps are required: a single step modifies at most one entry, so convertingn - ones_countnon-1entries into1requires at leastn - ones_countsteps. - Why
n - ones_countsteps always suffice: as long as any non-1entry remains, at least one boundary pairs a1right next to a non-1valuex. Overwritingxwithgcd(1, x) = 1eliminates one non-1entry per step!
nums = [8, 1, 6, 1, 12] (n = 5, ones_count = 2 -> 5 - 2 = 3 steps) step 1: pair (0, 1) -> overwrite 8 with gcd(8, 1) = 1 -> [1, 1, 6, 1, 12] step 2: pair (1, 2) -> overwrite 6 with gcd(1, 6) = 1 -> [1, 1, 1, 1, 12] step 3: pair (3, 4) -> overwrite 12 with gcd(1, 12) = 1 -> [1, 1, 1, 1, 1](When
ones_count == n,n - ones_count = 0, handling an already all-ones input automatically.)ones_count = 0 for value in nums: if value == 1: ones_count += 1 if ones_count > 0: return n - ones_count- Why at least
Case 2: no `1` exists yet — find the shortest subarray with GCD `1`
Now suppose zero entries equal
1. Before spreading1s, we must build our very first1. Letshortest_lenbe the length of the shortest contiguous subarraynums[start .. end]whose combined GCD equals1.1. How to create a
1inshortest_len - 1steps: Sweep across that window from left to right, each time overwriting the right neighbor with the running GCD:Window of length L = 3: [ 10, 14, 35 ] step 1 on (0, 1): [ 10, gcd(10,14)=2, 35 ] step 2 on (1, 2): [ 10, 2, gcd(2,35)=1 ] <-- first 1 after L - 1 = 2 steps!Right after step
shortest_len - 1finishes, the array contains one1andn - 1non-1entries, so Case 1 converts the rest inn - 1additional steps —(shortest_len - 1) + (n - 1)steps in total.2. Why no sequence of steps can do fewer: Consider the step
tthat writes the very first1anywhere in the array: - That1can only arise by combining elements from some contiguous span[A .. B]whose collective GCD is1, soB - A + 1 >= shortest_len. Information can cross across[A .. B]only if allB - Aadjacent boundaries inside[A .. B]were used at least once — meaningt >= B - A >= shortest_len - 1. - Immediately after steptproduces that first1, the othern - 1positions are still greater than1, and each subsequent step updates at most one position — requiring at leastn - 1further steps!Thus
(shortest_len - 1) + (n - 1)is provably minimal. If no subarray reaches GCD1, the whole array shares a divisor> 1, so we return-1.Code the shortest-window search
For each
startindex (0 .. n - 1), advanceendrightward while maintainingrunning_gcd. Becausemath.gcd(0, x)evaluates toxin Python, initializingrunning_gcd = 0cleanly seeds the 1-element window GCD tonums[start]. Oncerunning_gcd == 1, recordend - start + 1andbreakout of the inner loop since extendingendfurther from the samestartonly produces longer windows.from math import gcd def shortest_window_with_gcd_one(nums: list[int]) -> int: """Return the length of the shortest contiguous subarray with GCD 1, or 0 if none.""" n = len(nums) # shortest_len: minimum window length end - start + 1 whose combined GCD is 1 (0 means none found) shortest_len = 0 for start in range(n): # gcd(0, x) == x in Python, so starting at 0 seeds running_gcd with nums[start]. running_gcd = 0 for end in range(start, n): running_gcd = gcd(running_gcd, nums[end]) if running_gcd == 1: window_len = end - start + 1 if shortest_len == 0 or window_len < shortest_len: shortest_len = window_len # Extending `end` further from this `start` can only make longer windows. break return shortest_lenPut the phases together and trace a tricky trap
Notice why Phase 1 (
ones_count > 0) must run before Phase 2: onnums = [8, 1, 6, 1, 12],shortest_window_with_gcd_onewould report[1]of length1, and(1 - 1) + (5 - 1)would wrongly return4instead of5 - 2 = 3!Also verify why testing every
startindex matters onnums = [10, 14, 35, 9](n = 4):start = 0: 10 -> gcd(10,14)=2 -> gcd(2,35)=1 (window [10, 14, 35], length = 3) start = 1: 14 -> gcd(14,35)=7 -> gcd(7,9)=1 (window [14, 35, 9], length = 3) start = 2: 35 -> gcd(35,9)=1 (window [35, 9], length = 2 <-- shortest!) start = 3: 9 (never reaches 1) shortest_len = 2 -> total steps = (2 - 1) + (4 - 1) = 4 (stopping at start=0 would give 5!)Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from math import gcd def shortest_window_with_gcd_one(nums: list[int]) -> int: """Return the length of the shortest contiguous subarray with GCD 1, or 0 if none.""" n = len(nums) # shortest_len: minimum window length end - start + 1 whose combined GCD is 1 (0 means none found) shortest_len = 0 for start in range(n): # gcd(0, x) == x in Python, so starting at 0 seeds running_gcd with nums[start]. running_gcd = 0 for end in range(start, n): running_gcd = gcd(running_gcd, nums[end]) if running_gcd == 1: window_len = end - start + 1 if shortest_len == 0 or window_len < shortest_len: shortest_len = window_len # Extending `end` further from this `start` can only make longer windows. break return shortest_len def min_operations_to_all_ones(nums: list[int]) -> int: n = len(nums) # Phase 1: If at least one 1 already exists, each non-1 element takes 1 operation # to convert by spreading outward via gcd(1, x) = 1. Must check BEFORE Phase 2! ones_count = 0 for value in nums: if value == 1: ones_count += 1 if ones_count > 0: return n - ones_count # Phase 2: No 1 exists yet, so find the shortest contiguous subarray with GCD 1. shortest_len = shortest_window_with_gcd_one(nums) if shortest_len == 0: # Every element shares a common factor > 1, so 1 can never be formed. return -1 # Phase 3: (shortest_len - 1) operations fold that window into our first 1, # leaving (n - 1) other positions that each take 1 operation to become 1. ops_to_create_first_one = shortest_len - 1 ops_to_spread_one = n - 1 return ops_to_create_first_one + ops_to_spread_one✅ Submit now — all tests should pass.
Intuition & how it works
Think of 1 as a contagious "spark": because the greatest common divisor (GCD) (the largest positive integer dividing two numbers without remainder) satisfies gcd(1, x) = 1 for every positive integer x, once even one 1 sits anywhere in nums, it converts an adjacent neighbor to 1 in a single step, then the next neighbor in a single step, and so on across the array. That divides the problem into two clean cases:
1. At least one 1 is already present (ones_count > 0): Every step overwrites only one slot, so the remaining n - ones_count non-1 entries take exactly n - ones_count steps.
2. No 1 is present (ones_count == 0): We first manufacture our first 1 in as few steps as possible. Folding a contiguous subarray (an unbroken slice nums[start .. end]) of length L that is coprime collectively (the GCD across all L values together equals 1) takes L - 1 neighbor steps to produce 1, and right after that first 1 appears, the remaining n - 1 slots each need 1 step — totaling (L - 1) + (n - 1) steps where L is minimized.
Why do obvious approaches fail? Running breadth-first search (BFS) (exploring every reachable array state level by level) blows up exponentially because 50 slots can form vast combinations of intermediate subarray GCDs. Meanwhile, checking only adjacent pairs (gcd(nums[i], nums[i + 1]) == 1) fails on inputs such as [10, 14, 35], where no adjacent pair is coprime (gcd(10, 14) = 2 and gcd(14, 35) = 7), yet combining all three yields gcd(2, 35) = 1!
Here is a step-by-step trace on nums = [10, 14, 35, 9] (n = 4):
1. Count existing 1s: ones_count = 0 (must manufacture our first 1).
2. Scan every start index for the shortest contiguous window with GCD 1:
- start = 0: 10 -> gcd=2 (at 14) -> gcd=1 (at 35) => length 3 ([10, 14, 35])
- start = 1: 14 -> gcd=7 (at 35) -> gcd=1 (at 9) => length 3 ([14, 35, 9])
- start = 2: 35 -> gcd=1 (at 9) => length 2 ([35, 9]) <-- shortest!
- start = 3: 9 => never reaches 1
3. Build & spread:
- Create first 1 from [35, 9] in (2 - 1) = 1 step: [10, 14, 35, 1]
- Spread that 1 to the other (4 - 1) = 3 slots: [10, 14, 1, 1] -> [10, 1, 1, 1] -> [1, 1, 1, 1]
- Total = 1 + 3 = 4 steps.
Complexity
Let n be len(nums) (2 <= n <= 50) and V be max(nums) (V <= 10^6).
- Time:
O(n^2 log V). Counting ones scans thenentries once inO(n)time. The nested(start, end)loops inspect at mostn(n + 1) / 2windows (1,275windows whenn = 50), doing onegcdcall per step; by the Euclidean algorithm (which repeatedly replaces(a, b)with(b, a % b)), eachgcdtakesO(log V)divisions (at most ~20 steps forV <= 10^6) — and even less amortized across each inner loop because a running GCD can drop to a proper divisor at mostlog2(V)times! - Space:
O(1)auxiliary space (extra memory beyond the input array). Only scalar integer variables (ones_count,shortest_len,running_gcd, loop indices) are allocated.
Edge cases
- Already all
1s ([1, 1, 1]):ones_count == n, so Phase 1 returnsn - n = 0immediately. - Multiple
1s mixed with non-coprime numbers ([1, 4, 4]or[8, 1, 6, 1, 12]): Even when non-1entries share factors, existing1s convert them directly viagcd(1, x) = 1, returningn - ones_count. - Whole array shares a prime factor (
[9, 15, 21, 6]): Every window GCD remains divisible by3,shortest_lenstays0, and the function returns-1. - Shortest window sits near the end (
[10, 14, 35, 9]): Starting at index0finds length3, whereas index2([35, 9]) finds length2, saving a step (4instead of5). - Only the full array has GCD
1([105, 70, 42, 30], where each entry omits one prime from{2, 3, 5, 7}): Every shorter slice shares the omitted prime;shortest_len = 4, giving(4 - 1) + (4 - 1) = 6.
Common mistakes
- Skipping the
ones_count > 0check and applying(shortest_len - 1) + (n - 1)unconditionally: When two or more1s already exist (such as[8, 1, 6, 1, 12]),shortest_lenis1, and(1 - 1) + (5 - 1) = 4overcounts because existing1s never need overwriting! - Using
shortest_leninstead ofshortest_len - 1for the creation cost: FoldingLneighboring entries requiresL - 1pairwise steps (2 entries take 1 GCD step, 3 entries take 2, etc.). - Checking only adjacent pairs (
L = 2): Fails whenever pairwise GCDs exceed1while a 3-element or 4-element subarray has GCD1(Example 1:[10, 14, 35]). - Returning as soon as the first GCD-1 window is found: A window starting at
start = 0is not necessarily the shortest window innums.
Alternative approaches
- Distinct subarray GCD deduplication (
O(n log V)GCD calls): For a fixed right endpointend, the running GCDs of all subarraysnums[start .. end]assume at mostfloor(log2(V)) + 1 <= 21distinct values, since each drop divides the GCD by at least2. Maintaining a compact list of(gcd_val, latest_start_index)pairs per index findsshortest_leninO(n log^2 V)time — unnecessary forn <= 50, yet essential ifn = 10^5. - Sparse table + binary search (
O(n log n log V)): Because subarray GCD is monotonic (expanding a window only shrinks or preserves its GCD), you can build a sparse table (a 2D lookup table precomputing GCDs over power-of-two lengths1, 2, 4, 8, ...forO(1)range-GCD queries) and binary-search the smallest validendperstart.
Follow-up questions
- How would you extend the function to return an actual optimal sequence of replacement steps rather than only the step count? Follow the constructive two-phase proof directly: when
ones_count == 0, record(i, i + 1, overwrite=i + 1)forifrombest_starttobest_end - 1across the shortest GCD-1 window[best_start .. best_end], leaving a1atbest_end. Once at least one1exists, sweep left-to-right from any1to convert non-1right neighbors and sweep right-to-left from any1to convert non-1left neighbors, emitting the exact minimal number of steps. - What if len(nums) could reach 100,000, making an O(n^2) subarray scan too slow? Replace
shortest_window_with_gcd_onewith the distinct suffix-GCD list technique: iterateendfrom0ton - 1, map each(g, latest_start)from the prior step to(gcd(g, nums[end]), latest_start), merge equal GCDs by keeping the largestlatest_start, and wheneverg == 1appears, updateshortest_lenwithend - latest_start + 1. Because at most ~20 distinct GCDs survive at eachend, total runtime drops toO(n log^2 V). - How does the answer change if each move may combine any two indices (i, j) in the array instead of only adjacent indices? Without adjacency constraints, manufacturing the first
1costsk - 1steps wherekis the size of the smallest subset (not contiguous subarray) whose GCD is1, yielding(k - 1) + (n - 1)whenones_count == 0. Since no integer<= 10^6has more than7distinct prime factors (2 * 3 * 5 * 7 * 11 * 13 * 17 = 510,510),k <= 8, and you can computekvia dynamic programmingmin_subset_size[g]over reachable GCD states.
Follow-up questions
- How would you extend the function to return an actual optimal sequence of replacement steps rather than only the step count?
- What if len(nums) could reach 100,000, making an O(n^2) subarray scan too slow?
- How does the answer change if each move may combine any two indices (i, j) in the array instead of only adjacent indices?
Similar questions
- Evaluate Infix Arithmetic Expressions
- Fixed-Width Line Justification
- Infix Arithmetic Expression Evaluator
- Scoped Key-Value Store Supporting Nested Transactions
- Multi-Rule Password Validator
- Presenting and Justifying a Production Data Pipeline Architecture
More Otter.Ai interview questions
- Fault-Tolerant Meeting Bot Dispatch and Lifecycle Service Medium
- Real-Time Collaborative Document Editor Backend Medium
- Presenting and Justifying a Production Data Pipeline Architecture Medium Pro
- Evaluate Infix Arithmetic Expressions Medium Pro
- Versioned Key-Value Store with Snapshot Commits and Rollover Compaction Easy Pro
- Projects Tied for Largest Headcount Medium Pro
- Top Earners per Department Medium Pro
- Fixed-Width Line Justification Medium Pro
- Infix Arithmetic Expression Evaluator Medium Pro
- Scoped Key-Value Store Supporting Nested Transactions Medium Pro