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 both a and b (for instance, gcd(14, 21) = 7 and gcd(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 nums is already 1, 0 steps 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) <= 50
  • 1 <= nums[i] <= 10^6

Step-by-step walkthrough

  1. Understand the operation and two GCD rules

    In each step, we pick two neighboring indices i and i + 1 and overwrite one of them (never both at once!) with gcd(nums[i], nums[i + 1]). Two fundamental properties of greatest common divisors unlock the problem:

    1. Once you have a 1, it spreads in 1 step per neighbor: gcd(1, x) = 1 for every positive integer x, so a 1 sitting beside any value x converts x into 1 in one step.
    2. A shared factor across the entire array can never vanish: when every element in nums is a multiple of some d > 1 (such as [9, 15, 21, 6] with d = 3), every GCD ever formed stays divisible by d, making 1 unreachable (-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)
    
  2. 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 with n. At n = 50, state-space search cannot finish in time — we need a direct mathematical formula.

  3. Case 1: at least one `1` is already present

    Suppose nums already contains ones_count >= 1 copies of 1, leaving n - ones_count entries strictly greater than 1.

    • Why at least n - ones_count steps are required: a single step modifies at most one entry, so converting n - ones_count non-1 entries into 1 requires at least n - ones_count steps.
    • Why n - ones_count steps always suffice: as long as any non-1 entry remains, at least one boundary pairs a 1 right next to a non-1 value x. Overwriting x with gcd(1, x) = 1 eliminates one non-1 entry 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
    
  4. Case 2: no `1` exists yet — find the shortest subarray with GCD `1`

    Now suppose zero entries equal 1. Before spreading 1s, we must build our very first 1. Let shortest_len be the length of the shortest contiguous subarray nums[start .. end] whose combined GCD equals 1.

    1. How to create a 1 in shortest_len - 1 steps: 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 - 1 finishes, the array contains one 1 and n - 1 non-1 entries, so Case 1 converts the rest in n - 1 additional steps — (shortest_len - 1) + (n - 1) steps in total.

    2. Why no sequence of steps can do fewer: Consider the step t that writes the very first 1 anywhere in the array: - That 1 can only arise by combining elements from some contiguous span [A .. B] whose collective GCD is 1, so B - A + 1 >= shortest_len. Information can cross across [A .. B] only if all B - A adjacent boundaries inside [A .. B] were used at least once — meaning t >= B - A >= shortest_len - 1. - Immediately after step t produces that first 1, the other n - 1 positions are still greater than 1, and each subsequent step updates at most one position — requiring at least n - 1 further steps!

    Thus (shortest_len - 1) + (n - 1) is provably minimal. If no subarray reaches GCD 1, the whole array shares a divisor > 1, so we return -1.

  5. Code the shortest-window search

    For each start index (0 .. n - 1), advance end rightward while maintaining running_gcd. Because math.gcd(0, x) evaluates to x in Python, initializing running_gcd = 0 cleanly seeds the 1-element window GCD to nums[start]. Once running_gcd == 1, record end - start + 1 and break out of the inner loop since extending end further from the same start only 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_len
    
  6. Put the phases together and trace a tricky trap

    Notice why Phase 1 (ones_count > 0) must run before Phase 2: on nums = [8, 1, 6, 1, 12], shortest_window_with_gcd_one would report [1] of length 1, and (1 - 1) + (5 - 1) would wrongly return 4 instead of 5 - 2 = 3!

    Also verify why testing every start index matters on nums = [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!)
    
  7. 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 the n entries once in O(n) time. The nested (start, end) loops inspect at most n(n + 1) / 2 windows (1,275 windows when n = 50), doing one gcd call per step; by the Euclidean algorithm (which repeatedly replaces (a, b) with (b, a % b)), each gcd takes O(log V) divisions (at most ~20 steps for V <= 10^6) — and even less amortized across each inner loop because a running GCD can drop to a proper divisor at most log2(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 returns n - n = 0 immediately.
  • Multiple 1s mixed with non-coprime numbers ([1, 4, 4] or [8, 1, 6, 1, 12]): Even when non-1 entries share factors, existing 1s convert them directly via gcd(1, x) = 1, returning n - ones_count.
  • Whole array shares a prime factor ([9, 15, 21, 6]): Every window GCD remains divisible by 3, shortest_len stays 0, and the function returns -1.
  • Shortest window sits near the end ([10, 14, 35, 9]): Starting at index 0 finds length 3, whereas index 2 ([35, 9]) finds length 2, saving a step (4 instead of 5).
  • 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 > 0 check and applying (shortest_len - 1) + (n - 1) unconditionally: When two or more 1s already exist (such as [8, 1, 6, 1, 12]), shortest_len is 1, and (1 - 1) + (5 - 1) = 4 overcounts because existing 1s never need overwriting!
  • Using shortest_len instead of shortest_len - 1 for the creation cost: Folding L neighboring entries requires L - 1 pairwise steps (2 entries take 1 GCD step, 3 entries take 2, etc.).
  • Checking only adjacent pairs (L = 2): Fails whenever pairwise GCDs exceed 1 while a 3-element or 4-element subarray has GCD 1 (Example 1: [10, 14, 35]).
  • Returning as soon as the first GCD-1 window is found: A window starting at start = 0 is not necessarily the shortest window in nums.

Alternative approaches

  • Distinct subarray GCD deduplication (O(n log V) GCD calls): For a fixed right endpoint end, the running GCDs of all subarrays nums[start .. end] assume at most floor(log2(V)) + 1 <= 21 distinct values, since each drop divides the GCD by at least 2. Maintaining a compact list of (gcd_val, latest_start_index) pairs per index finds shortest_len in O(n log^2 V) time — unnecessary for n <= 50, yet essential if n = 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 lengths 1, 2, 4, 8, ... for O(1) range-GCD queries) and binary-search the smallest valid end per start.

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) for i from best_start to best_end - 1 across the shortest GCD-1 window [best_start .. best_end], leaving a 1 at best_end. Once at least one 1 exists, sweep left-to-right from any 1 to convert non-1 right neighbors and sweep right-to-left from any 1 to convert non-1 left 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_one with the distinct suffix-GCD list technique: iterate end from 0 to n - 1, map each (g, latest_start) from the prior step to (gcd(g, nums[end]), latest_start), merge equal GCDs by keeping the largest latest_start, and whenever g == 1 appears, update shortest_len with end - latest_start + 1. Because at most ~20 distinct GCDs survive at each end, total runtime drops to O(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 1 costs k - 1 steps where k is the size of the smallest subset (not contiguous subarray) whose GCD is 1, yielding (k - 1) + (n - 1) when ones_count == 0. Since no integer <= 10^6 has more than 7 distinct prime factors (2 * 3 * 5 * 7 * 11 * 13 * 17 = 510,510), k <= 8, and you can compute k via dynamic programming min_subset_size[g] over reachable GCD states.

Follow-up questions

Similar questions

More Otter.Ai interview questions

All 12 Otter.Ai questions →