VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smallest-subarray-with-given-gcd/

⇱ Smallest Subarray with given GCD - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest Subarray with given GCD

Last Updated : 23 Jul, 2025

Given an array arr[] of n numbers and an integer k, find length of the minimum sub-array with gcd equals to k.
Example: 

Input: arr[] = {6, 9, 7, 10, 12, 
 24, 36, 27}, 
 K = 3
Output: 2
Explanation: GCD of subarray {6,9} is 3.
GCD of subarray {24,36,27} is also 3,
but {6,9} is the smallest 


Note: Time complexity analysis of below approaches assume that numbers are fixed size and finding GCD of two elements take constant time.
 

Recommended Practice

Find GCD of all subarrays and keep track of the minimum length subarray with gcd k. Time Complexity of this is O(n3), O(n2) for each subarray and O(n) for finding gcd of a subarray.

Method 2

Find GCD of all subarrays using segment tree based approach discussed here. Time complexity of this solution is O(n2logn), O(n2) for each subarray and O(logn) for finding GCD of subarray using segment tree.

Method 3

The idea is to use Segment Tree and Binary Search to achieve time complexity O(n (logn)2).

  1. If we have any number equal to ‘k’ in the array then the answer is 1 as GCD of k is k. Return 1.
  2. If there is no number which is divisible by k, then GCD doesn't exist. Return -1.
  3. If none of the above cases is true, the length of minimum subarray is either greater than 1 or GCD doesn't exist. In this case, we follow following steps. 
    • Build segment tree so that we can quickly find GCD of any subarray using the approach discussed here
    • After building Segment Tree, we consider every index as starting point and do binary search for ending point such that the subarray between these two points has GCD k

Following is the implementation of above idea. 


Output
Size of smallest sub-array with given size is 2

Example: 

arr[] = {6, 9, 7, 10, 12, 24, 36, 27}, K = 3

// Initial value of minLen is equal to size 
// of array
minLen = 8 

No element is equal to k so result is either 
greater than 1 or doesn't exist. 

First index

  • GCD of subarray from 1 to 5 is 1.
  • GCD < k
  • GCD of subarray from 1 to 3 is 1.
  • GCD < k
  • GCD of subarray from 1 to 2 is 3
  • minLen = minimum(8, 2) = 2

Second Index 

  • GCD of subarray from 2 to 5 is 1
  • GCD < k
  • GCD of subarray from 2 to 4 is 1
  • GCD < k
  • GCD of subarray from 6 to 8 is 3
  • minLen = minimum(2, 3) = 2.
     

.


 

.


 

.


 

Sixth Index


 

  • GCD of subarray from 6 to 7 is 12
  • GCD > k
  • GCD of subarray from 6 to 8 is 3
  • minLen = minimum(2, 3) = 2

Time Complexity: O(n (logn)2), O(n) for traversing to each index, O(logn) for each subarray and O(logn) for GCD of each subarray.

Space Complexity :  O(1)

Comment