#3605

Minimum Stability Factor of Array

Hard
ArrayMathBinary SearchGreedySegment TreeNumber TheoryHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

Use binary search to find the maximum length of stable subarrays, leveraging fast GCD queries to determine stability efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Binary search for the maximum length of stable subarrays (k).
  2. 2Step 2: For each k, check if it's possible to achieve stability with at most maxC modifications using a sliding window approach.
  3. 3Step 3: Use a segment tree or similar structure to efficiently compute GCD over subarray ranges.
solution.py13 lines
1def min_stability_factor(nums, maxC):
2    def canAchieve(k):
3        count = 0
4        for i in range(len(nums) - k + 1):
5            if gcd(*nums[i:i+k]) < 2:
6                count += 1
7        return count <= maxC
8    left, right = 1, len(nums)
9    while left < right:
10        mid = (left + right) // 2
11        if canAchieve(mid): right = mid
12        else: left = mid + 1
13    return left

Complexity note: Binary search reduces the problem size logarithmically, while GCD checks are linear.

  • 1Stable subarrays require HCF >= 2.
  • 2Modifications can strategically increase stability.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.