Split array into minimum number of subarrays having GCD of its first and last element exceeding 1

Given an array arr[] of size N, the task is to split the entire array into a minimum number of subarrays such that for each subarray, the GCD of the first and last element of the subarray is greater than 1.
Examples:
Input: arr[] = {2, 3, 4, 4, 4, 3}Â
Output: 2Â
Explanation:Â
Split the given array into [2, 3, 4, 4, 4] and [3].Â
The first subarray has gcd(2, 4) = 2 which is more than 1 andÂ
The second subarray has gcd(3, 3) = 3 which is also more than 1.Input: arr[] = {1, 2, 3}Â
Output: 0Â
Explanation:Â
There is no possible splitting of the given array into subarrays in which the GCD of first and last element of the subarray is more than 1.
Naive Approach: The simplest approach to solve the problem is to perform all possible splits in the given array and for each split, check if all the subarrays have GCD of its first and last element greater than 1 or not. For all subarrays for which it is found to be true, store the count of subarrays. Finally, print the minimum count obtained among those splits.
Time Complexity: O(2N)Â
Auxiliary Space: O(1)Â
Efficient Approach: The approach is based on the idea that the first and the last element of the original array will always be used. The first element will be used in the first subarray split, the last element will be used in the last subarray split. To minimize the count of valid subarrays, follow the steps below:
- Fix a right pointer to the last element of the original array arr[], and find the leftmost element in the original array such that GCD(left, right) > 1. If such an element is not found, there is no valid answer.
- If such an element is found, that means we have found a valid subarray. Then change the right pointer to (left – 1), and again start searching for a valid subarray.
- Repeat the above step until right is more than 0 and keep on increasing the count of subarrays found till now.
- Print the value of count after all the above steps.
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 the// minimum number of subarraysint minSubarrays(int arr[], int n){    // Right pointer    int right = n - 1;Â
    // Left pointer    int left = 0;Â
    // Count of subarrays    int subarrays = 0;Â
    while (right >= 0) {Â
        for (left = 0; left <= right;             left += 1) {Â
            // Find GCD(left, right)            if (__gcd(arr[left],                      arr[right])                > 1) {Â
                // Found a valid large                // subarray between                // arr[left, right]                subarrays += 1;                right = left - 1;                break;            }Â
            // Searched the arr[0..right]            // and found no subarray            // having size >1 and having            // gcd(left, right) > 1            if (left == right                && __gcd(arr[left],                         arr[right])                       == 1) {                return 0;            }        }    }    return subarrays;}Â
// Driver Codeint main(){Â Â Â Â int N = 6;Â Â Â Â int arr[] = { 2, 3, 4, 4, 4, 3 };Â
    // Function call    cout << minSubarrays(arr, N);    return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{Â
// Function to find the// minimum number of subarraysstatic int minSubarrays(int arr[], int n){    // Right pointer    int right = n - 1;Â
    // Left pointer    int left = 0;Â
    // Count of subarrays    int subarrays = 0;Â
    while (right >= 0)     {        for (left = 0; left <= right; left += 1)         {            // Find GCD(left, right)            if (__gcd(arr[left],                      arr[right]) > 1)             {                // Found a valid large                // subarray between                // arr[left, right]                subarrays += 1;                right = left - 1;                break;            }Â
            // Searched the arr[0..right]            // and found no subarray            // having size >1 and having            // gcd(left, right) > 1            if (left == right &&                 __gcd(arr[left],                arr[right]) == 1)             {                return 0;            }        }    }    return subarrays;}static int __gcd(int a, int b) {     return b == 0 ? a : __gcd(b, a % b);    }// Driver Codepublic static void main(String[] args){    int N = 6;    int arr[] = {2, 3, 4, 4, 4, 3};Â
    // Function call    System.out.print(minSubarrays(arr, N));}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 program for the above approachfrom math import gcdÂ
# Function to find the# minimum number of subarraysdef minSubarrays(arr, n):         # Right pointer    right = n - 1Â
    # Left pointer    left = 0Â
    # Count of subarrays    subarrays = 0Â
    while (right >= 0):        for left in range(right + 1):Â
            # Find GCD(left, right)            if (gcd(arr[left], arr[right]) > 1):Â
                # Found a valid large                # subarray between                # arr[left, right]                subarrays += 1                right = left - 1                breakÂ
            # Searched the arr[0..right]            # and found no subarray            # having size >1 and having            # gcd(left, right) > 1            if (left == right and                __gcd(arr[left],                       arr[right]) == 1):                return 0Â
    return subarraysÂ
# Driver Codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â N = 6Â Â Â Â arr = [ 2, 3, 4, 4, 4, 3 ]Â
    # Function call    print(minSubarrays(arr, N))     # This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;class GFG{Â
// Function to find the// minimum number of subarraysstatic int minSubarrays(int[] arr, int n){    // Right pointer    int right = n - 1;Â
    // Left pointer    int left = 0;Â
    // Count of subarrays    int subarrays = 0;Â
    while (right >= 0)     {        for (left = 0; left <= right; left += 1)         {            // Find GCD(left, right)            if (__gcd(arr[left],                      arr[right]) > 1)             {                // Found a valid large                // subarray between                // arr[left, right]                subarrays += 1;                right = left - 1;                break;            }Â
            // Searched the arr[0..right]            // and found no subarray            // having size >1 and having            // gcd(left, right) > 1            if (left == right &&                 __gcd(arr[left],                      arr[right]) == 1)             {                return 0;            }        }    }    return subarrays;}   static int __gcd(int a, int b) {     return b == 0 ? a : __gcd(b, a % b);    }   // Driver Codepublic static void Main(){    int N = 6;    int[] arr = {2, 3, 4, 4, 4, 3};Â
    // Function call    Console.Write(minSubarrays(arr, N));}}Â
// This code is contributed by Chitranayal |
Javascript
<script>// javascript program for the above approachÂ
    // Function to find the    // minimum number of subarrays    function minSubarrays(arr , n) {        // Right pointer        var right = n - 1;Â
        // Left pointer        var left = 0;Â
        // Count of subarrays        var subarrays = 0;Â
        while (right >= 0) {            for (left = 0; left <= right; left += 1) {                // Find GCD(left, right)                if (__gcd(arr[left], arr[right]) > 1) {                    // Found a valid large                    // subarray between                    // arr[left, right]                    subarrays += 1;                    right = left - 1;                    break;                }Â
                // Searched the arr[0..right]                // and found no subarray                // having size >1 and having                // gcd(left, right) > 1                if (left == right && __gcd(arr[left], arr[right]) == 1) {                    return 0;                }            }        }        return subarrays;    }Â
    function __gcd(a , b) {        return b == 0 ? a : __gcd(b, a % b);    }Â
    // Driver Code             var N = 6;        var arr = [ 2, 3, 4, 4, 4, 3 ];Â
        // Function call        document.write(minSubarrays(arr, N));Â
// This code contributed by umadevi9616 </script> |
2
Time Complexity: O()Â
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



