LeetCode #3605 — HARD

Minimum Stability Factor of Array

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer array nums and an integer maxC.

A subarray is called stable if the highest common factor (HCF) of all its elements is greater than or equal to 2.

The stability factor of an array is defined as the length of its longest stable subarray.

You may modify at most maxC elements of the array to any integer.

Return the minimum possible stability factor of the array after at most maxC modifications. If no stable subarray remains, return 0.

Note:

  • The highest common factor (HCF) of an array is the largest integer that evenly divides all the array elements.
  • A subarray of length 1 is stable if its only element is greater than or equal to 2, since HCF([x]) = x.

Example 1:

Input: nums = [3,5,10], maxC = 1

Output: 1

Explanation:

  • The stable subarray [5, 10] has HCF = 5, which has a stability factor of 2.
  • Since maxC = 1, one optimal strategy is to change nums[1] to 7, resulting in nums = [3, 7, 10].
  • Now, no subarray of length greater than 1 has HCF >= 2. Thus, the minimum possible stability factor is 1.

Example 2:

Input: nums = [2,6,8], maxC = 2

Output: 1

Explanation:

  • The subarray [2, 6, 8] has HCF = 2, which has a stability factor of 3.
  • Since maxC = 2, one optimal strategy is to change nums[1] to 3 and nums[2] to 5, resulting in nums = [2, 3, 5].
  • Now, no subarray of length greater than 1 has HCF >= 2. Thus, the minimum possible stability factor is 1.

Example 3:

Input: nums = [2,4,9,6], maxC = 1

Output: 2

Explanation:

  • The stable subarrays are:
    • [2, 4] with HCF = 2 and stability factor of 2.
    • [9, 6] with HCF = 3 and stability factor of 2.
  • Since maxC = 1, the stability factor of 2 cannot be reduced due to two separate stable subarrays. Thus, the minimum possible stability factor is 2.

Constraints:

  • 1 <= n == nums.length <= 105
  • 1 <= nums[i] <= 109
  • 0 <= maxC <= n
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer array nums and an integer maxC. A subarray is called stable if the highest common factor (HCF) of all its elements is greater than or equal to 2. The stability factor of an array is defined as the length of its longest stable subarray. You may modify at most maxC elements of the array to any integer. Return the minimum possible stability factor of the array after at most maxC modifications. If no stable subarray remains, return 0. Note: The highest common factor (HCF) of an array is the largest integer that evenly divides all the array elements. A subarray of length 1 is stable if its only element is greater than or equal to 2, since HCF([x]) = x.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Math · Binary Search · Greedy · Segment Tree

Example 1

[3,5,10]
1

Example 2

[2,6,8]
2

Example 3

[2,4,9,6]
1
Step 02

Core Insight

What unlocks the optimal approach

  • Binary‐search the target length <code>k</code>
  • For each <code>k</code>, use fast range‐GCD queries
  • Greedily "hit" every window of size <code>k+1</code> with an edit if its <code>GCD > 1</code>
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3605: Minimum Stability Factor of Array
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3605: Minimum Stability Factor of Array
// package main
// 
// import (
// 	"sort"
// )
// 
// // https://space.bilibili.com/206214
// func minStable1(nums []int, maxC int) int {
// 	n := len(nums)
// 	leftMin := make([]int, n)
// 	type interval struct{ gcd, l int } // 子数组 GCD,最小左端点
// 	intervals := []interval{{1, 0}}    // 哨兵
// 	for i, x := range nums {
// 		// 计算以 i 为右端点的子数组 GCD
// 		for j, p := range intervals {
// 			intervals[j].gcd = gcd(p.gcd, x)
// 		}
// 		// nums[i] 单独一个数作为子数组
// 		intervals = append(intervals, interval{x, i})
// 
// 		// 去重(合并 GCD 相同的区间)
// 		idx := 1
// 		for j := 1; j < len(intervals); j++ {
// 			if intervals[j].gcd != intervals[j-1].gcd {
// 				intervals[idx] = intervals[j]
// 				idx++
// 			}
// 		}
// 		intervals = intervals[:idx]
// 
// 		// 由于我们添加了哨兵,intervals[1] 的 GCD >= 2 且最长,取其区间左端点作为子数组的最小左端点
// 		if len(intervals) > 1 {
// 			leftMin[i] = intervals[1].l
// 		} else {
// 			leftMin[i] = n
// 		}
// 	}
// 
// 	ans := sort.Search(n/(maxC+1), func(upper int) bool {
// 		c := maxC
// 		i := upper
// 		for i < n {
// 			if i-leftMin[i]+1 > upper {
// 				if c == 0 {
// 					return false
// 				}
// 				c--
// 				i += upper + 1
// 			} else {
// 				i++
// 			}
// 		}
// 		return true
// 	})
// 	return ans
// }
// 
// func minStable(nums []int, maxC int) int {
// 	n := len(nums)
// 	leftMin := make([]int, n)
// 	var left, bottom, rightGcd int
// 	for i, x := range nums {
// 		rightGcd = gcd(rightGcd, x)
// 		for left <= i && gcd(nums[left], rightGcd) == 1 {
// 			if bottom <= left {
// 				// 重新构建一个栈
// 				// 由于 left 即将移出窗口,只需计算到 left+1
// 				for j := i - 1; j > left; j-- {
// 					nums[j] = gcd(nums[j], nums[j+1])
// 				}
// 				bottom = i
// 				rightGcd = 0
// 			}
// 			left++
// 		}
// 		leftMin[i] = left
// 	}
// 
// 	ans := sort.Search(n/(maxC+1), func(upper int) bool {
// 		c := maxC
// 		i := upper
// 		for i < n {
// 			if i-leftMin[i]+1 > upper {
// 				if c == 0 {
// 					return false
// 				}
// 				c--
// 				i += upper + 1
// 			} else {
// 				i++
// 			}
// 		}
// 		return true
// 	})
// 	return ans
// }
// 
// func gcd(a, b int) int { for a != 0 { a, b = b%a, a }; return b }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

LINEAR SCAN
O(n) time
O(1) space

Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.

BINARY SEARCH
O(log n) time
O(1) space

Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).

Shortcut: Halving the input each step → O(log n). Works on any monotonic condition, not just sorted arrays.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

Boundary update without `+1` / `-1`

Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.

Usually fails on: Two-element ranges never converge.

Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.