Given an array arr[] consisting of N elements and an arrayQ[], the task for each query is to find the length of the longest prefix such that all the elements of this prefix are divisible by K.
Examples:
Input: arr[] = {12, 6, 15, 3, 10}, Q[] = {4, 3, 2}
Output: 1 4 2
Explanation:
- Q[0] = 4: arr[0] (= 12) is divisible by 4. arr[1] is not divisible by 4. Therefore, the length of the longest prefix divisible by 4 is 1.
- Q[1] = 3: The longest prefix which is divisible by 3 is {12, 6, 15, 3}. Therefore, print 4 as the required output.
- Q[2] = 2: The longest prefix which is divisible by 2 is {12, 6}.
Input: arr[] = {4, 3, 2, 1}, Q[] = {1, 2, 3}
Output: 4 1 0
Approach: The idea is to observe that if the first i elements of the array are divisible by the given integer K, then their GCD will also be divisible by K. Follow the steps below to solve the problem:
- Before finding the answer to each query, pre-compute the gcd of the prefixes of the array in another array g[] such that g[0] = arr[0] and for rest of the elements g[i] = GCD(arr[i], g[i – 1]).
- Then for each element in the array Q[], perform Binary Search on the array g[] and find the last index of g[] which is divisible by Q[i].
- It has to be noted that all the elements before this index will be divisible by K, since the gcd of all the elements till this index is divisible by K.
- Print the length of the longest prefix.
Below is the implementation of the above approach.
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find index of the last // element which is divisible the given element int binSearch(int* g, int st, int en, int val) { // Initially assume the // index to be -1 int ind = -1; while (st <= en) { // Find the mid element // of the subarray int mid = st + (en - st) / 2; // If the mid element is divisible by // given element, then move to right // of mid and update ind to mid if (g[mid] % val == 0) { ind = mid; st = mid + 1; } // Otherwise, move to left of mid else { en = mid - 1; } } // Return the length of prefix return ind + 1; } // Function to compute and print for each query void solveQueries(int* arr, int* queries, int n, int q) { int g[n]; // Pre compute the gcd of the prefixes // of the input array in the array g[] for (int i = 0; i < n; i++) { if (i == 0) { g[i] = arr[i]; } else { g[i] = __gcd(g[i - 1], arr[i]); } } // Perform binary search // for each query for (int i = 0; i < q; i++) { cout << binSearch(g, 0, n - 1, queries[i]) << " "; } } // Driver Code int main() { // Given array int arr[] = { 12, 6, 15, 3, 10 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); // Given Queries int queries[] = { 4, 3, 2 }; // Size of queries int q = sizeof(queries) / sizeof(queries[0]); solveQueries(arr, queries, n, q); } |
1 4 2
Time Complexity: O(NlogN + QlogN)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Pair of strings having longest common prefix of maximum length in given array
- Construct an Array of Strings having Longest Common Prefix specified by the given Array
- Length of longest subsequence having absolute difference of all pairs divisible by K
- Length of longest common prefix possible by rearranging strings in a given array
- Count sequences of given length having non-negative prefix sums that can be generated by given values
- Queries to find longest subsequence having no smilar adjacent elements with updates
- Length of longest subsequence in an Array having all elements as Nude Numbers
- Find the word from a given sentence having given word as prefix
- Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree
- Count of binary strings of length N having equal count of 0's and 1's and count of 1's ≥ count of 0's in each prefix substring
- Subarray of length K having concatenation of its elements divisible by X
- Longest string in an array which matches with prefix of the given string
- Length of longest substring having all characters as K
- Maximize length of longest non-decreasing array possible by the elements present in either ends of the given array
- Find the longest sub-string which is prefix, suffix and also present inside the string
- Longest prefix that contains same number of X and Y in an array
- Minimize length of prefix of string S containing all characters of another string T
- Queries for elements having values within the range A to B in the given index range using Segment Tree
- Queries to find maximum sum contiguous subarrays of given length in a rotating array
- Queries to calculate the Sum of Array elements in the range [L, R] having indices as multiple of K
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

