Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Hard
  • Last Updated : 10 Aug, 2021

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:
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:
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:



  1. 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.
  2. 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.
  3. Repeat the above step until right is more than 0 and keep on increasing the count of subarrays found till now.
  4. 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 subarrays
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;
}
 
// Driver Code
int 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 approach
import java.util.*;
class GFG{
 
// Function to find the
// minimum number of subarrays
static 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 Code
public 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 approach
from math import gcd
 
# Function to find the
# minimum number of subarrays
def 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 Code
if __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 approach
using System;
class GFG{
 
// Function to find the
// minimum number of subarrays
static 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 Code
public 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>
Output: 
2

Time Complexity: O(N^2
Auxiliary Space: O(1)

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :