## Wednesday, June 15, 2016

### Smallest Subarray with given GCD - GeeksforGeeks

Smallest Subarray with given GCD - GeeksforGeeks
Given an array arr[] of n numbers and an integer k, find length of the minimum sub-array with gcd equals to k.

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 quicky find GCD of any subarray using the approach discussedhere
• 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
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.

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.