![]() |
VOOZH | about |
Given an arrayarr[] consisting of N integers, the task is to find the maximum index K such that the product of subarrays{arr[0], arr[K]} and {arr[K + 1], arr[N - 1]} are co-prime. If no such index exists, then print "-1".
Examples:
Input: arr[] = {2, 3, 4, 5}
Output: 2
Explanation:
Smallest index for partition is 2.
Product of left subarray is = 2 * 3 * 4 = 24.
Product of right subarray = 5.
Since 24 and 5 are co-prime, the required answer is 2.Input: arr[] = {23, 41, 52, 83, 7, 13}
Output: 0
Explanation:
Smallest index for partition is 0.
Product of left subarray = 23.
Product of right subarray = 41 * 52 * 83 * 7 * 13 = 16102996.
Since 23 and 16102996 are co-prime, the answer is 0.
Naive Approach: The simplest approach is to check all possible indexes of partition from the start of the array and check if the product of the subarrays formed is co-prime or not. If there exists any such index then print that index. Otherwise, print "-1".
Time Complexity: O(N2)
Auxiliary Space: O(1)
Better Approach: To optimize the above approach, the idea is to use the prefix product array and suffix product array and find the possible index. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
2
Time Complexity: O(N log(N))
Auxiliary Space: O(N)
Efficient Approach: Above approach is using a prefix array and suffix array that stores the product of numbers , if the product of numbers exceeds the integer maximum value then it will lead to overflow , hence a different approach is needed such that it will work for every numbers that are present in the array. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
Output
2
Time Complexity: O(N*sqrt(N))
Auxiliary Space: O(N)