Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Divide an array into k subarrays with minimum cost II
Next article icon

Check if an array can be split into subarrays with GCD exceeding K

Last Updated : 20 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N integers and a positive integer K, the task is to check if it is possible to split this array into distinct contiguous subarrays such that the Greatest Common Divisor of all elements of each subarray is greater than K.

Note: Each array element can be a part of exactly one subarray.

Examples:

Input: arr[] = {3, 2, 4, 4, 8}, K = 1
Output: Yes
Explanation:
One valid split is [3], [2, 4], [4, 8] with GCD 3, 2 and 4 respectively. 
Another Valid Split is [3], [2, 4], [4], [8] with GCD 3, 2, 4 and 8 respectively.
Therefore, the given array can be split into subarrays having GCD > K.

Input: arr[] = {2, 4, 6, 1, 8, 16}, K = 3
Output: No

Approach: This problem can be solved using the following observations:

  • If any array element is found to be less than or equal to K, then the answer is always “No”. This is because the subarray that contains this number will always have GCD less than or equal to K.
  • If no array element is found to be less than or equal to K, then it is always possible to divide the entire array into N subarrays each of size at least 1 whose GCD is always greater than K.

Therefore, from the above observations, the idea is to traverse the given array and check that if there exists any element in the array which is less than or equal to K. If found to be true, then print “No”. Otherwise print “Yes”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <iostream>
using namespace std;
 
// Function to check if it is possible
// to split an array into subarrays
// having GCD at least K
string canSplitArray(int arr[], int n,
                     int k)
{
 
    // Iterate over the array arr[]
    for (int i = 0; i < n; i++) {
 
        // If the current element
        // is less than or equal to k
        if (arr[i] <= k) {
            return "No";
        }
    }
 
    // If no array element is found
    // to be less than or equal to k
    return "Yes";
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 2, 4, 6, 1, 8, 16 };
 
    int N = sizeof arr / sizeof arr[0];
 
    // Given K
    int K = 3;
 
    // Function Call
    cout << canSplitArray(arr, N, K);
}
 
 

Java




// Java program for the above approach
import java.io.*;
 
class GFG{
     
// Function to check if it is possible
// to split an array into subarrays
// having GCD at least K
static String canSplitArray(int arr[],
                            int n, int k)
{
     
    // Iterate over the array arr[]
    for(int i = 0; i < n; i++)
    {
         
        // If the current element
        // is less than or equal to k
        if (arr[i] <= k)
        {
            return "No";
        }
    }
     
    // If no array element is found
    // to be less than or equal to k
    return "Yes";
}
 
// Driver code
public static void main (String[] args)
{
     
    // Given array arr[]
    int arr[] = { 2, 4, 6, 1, 8, 16 };
     
    // Length of the array
    int N = arr.length;
     
    // Given K
    int K = 3;
     
    // Function call
    System.out.println(canSplitArray(arr, N, K));
}
}
 
// This code is contributed by jana_sayantan
 
 

Python3




# Python3 program for the above approach
 
# Function to check if it is possible
# to split an array into subarrays
# having GCD at least K
def canSplitArray(arr, n, k):
 
    # Iterate over the array arr[]
    for i in range(n):
 
        # If the current element
        # is less than or equal to k
        if (arr[i] <= k):
            return "No"
 
    # If no array element is found
    # to be less than or equal to k
    return "Yes"
 
# Driver Code
if __name__ == '__main__':
 
    # Given array arr[]
    arr = [ 2, 4, 6, 1, 8, 16 ]
 
    N = len(arr)
 
    # Given K
    K = 3
 
    # Function call
    print(canSplitArray(arr, N, K))
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
     
// Function to check if it is possible
// to split an array into subarrays
// having GCD at least K
static String canSplitArray(int []arr,
                            int n, int k)
{
     
    // Iterate over the array []arr
    for(int i = 0; i < n; i++)
    {
         
        // If the current element
        // is less than or equal to k
        if (arr[i] <= k)
        {
            return "No";
        }
    }
     
    // If no array element is found
    // to be less than or equal to k
    return "Yes";
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 2, 4, 6, 1, 8, 16 };
     
    // Length of the array
    int N = arr.Length;
     
    // Given K
    int K = 3;
     
    // Function call
    Console.WriteLine(canSplitArray(arr, N, K));
}
}
 
// This code is contributed by Amit Katiyar
 
 

Javascript




<script>
 
// JavaScript implementation of the above approach
 
// Function to check if it is possible
// to split an array into subarrays
// having GCD at least K
function canSplitArray(arr, n, k)
{
       
    // Iterate over the array arr[]
    for(let i = 0; i < n; i++)
    {
           
        // If the current element
        // is less than or equal to k
        if (arr[i] <= k)
        {
            return "No";
        }
    }
       
    // If no array element is found
    // to be less than or equal to k
    return "Yes";
}
 
// Driver code
         
    // Given array arr[]
    let arr = [ 2, 4, 6, 1, 8, 16 ];
       
    // Length of the array
    let N = arr.length;
       
    // Given K
    let K = 3;
       
    // Function call
    document.write(canSplitArray(arr, N, K));
       
    // This code is contributed by code_hunt.
</script>
 
 
Output: 
No

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



Next Article
Divide an array into k subarrays with minimum cost II

R

Ripunjoy Medhi
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
  • Searching
  • divisibility
  • GCD-LCM
  • HCF
  • subarray
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Searching

Similar Reads

  • Check if an array can be split into subsets of K consecutive elements
    Given an array arr[] and integer K, the task is to split the array into subsets of size K, such that each subset consists of K consecutive elements. Examples: Input: arr[] = {1, 2, 3, 6, 2, 3, 4, 7, 8}, K = 3 Output: true Explanation: The given array of length 9 can be split into 3 subsets {1, 2, 3}
    5 min read
  • Divide an array into k subarrays with minimum cost II
    Given an array of integers arr[] of length n and two positive integers kk and len. The cost of an array is the value of its first element. For example, the cost of [2,3,4] is 2 and the cost of [4,1,2] is 4. You have to divide arr[] into k disjoint contiguous subarrays such that the difference betwee
    11 min read
  • Check if an Array can be converted to other by replacing pairs with GCD
    Given arrays A[] and B[] each of length N and A[i] has all the elements from 1 to N, the task is to check if it is possible to convert A[] to B[] by replacing any pair of A[] with their GCD. Examples: Input: N = 2, A[] = {1, 2}, B[] = {1, 1}Output: YES Explanation:First Operation - For A[], choose i
    15+ min read
  • Check if a sorted array can be divided in pairs whose sum is k
    Given a sorted array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair k.Expected time complexity O(n) and extra space O(1). This problem is a variation of below problem, but has a different interesting solution that r
    11 min read
  • Check if Array has at least M non-overlapping Subarray with gcd G
    Given an array A[] and M, the task is to check whether there exist M non-overlapping subarrays(non-empty) of A for which the average of the GCD of those subarrays equals G where G denotes the gcd of all the numbers in the array A. Examples: Input: A[] = {1, 2, 3, 4, 5}, M = 3Output: Yes?Explanation:
    6 min read
  • Count ways to split array into two subarrays with equal GCD
    Given an array, arr[] of size N, the task is to count the number of ways to split given array elements into two subarrays such that GCD of both the subarrays are equal. Examples: Input: arr[] = {8, 4, 4, 8, 12} Output: 2 Explanation: Possible ways to split the array two groups of equal GCD are: { {{
    8 min read
  • Generate an array with product of all subarrays of length exceeding one divisible by K
    Given two positive integers N and K, the task is to generate an array of length N such that the product of every subarray of length greater than 1 must be divisible by K and the maximum element of the array must be less than K. If no such array is possible, then print -1. Examples: Input: N = 3, K =
    6 min read
  • Check if a Subarray exists with sums as a multiple of k
    Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer. Note: The length of the array won't exceed 10,000. You may assume th
    8 min read
  • Find an array of size N having exactly K subarrays with sum S
    Given three integers N, K and S, the task is to choose an array of size N such that there exists exactly K sub-arrays with sum S.Note: There can be many solution arrays to this problem.Examples: Input: N = 4, K = 2, S = 3 Output: 1 2 3 4 Explanation: One of the possible array is [ 1, 2, 3, 4 ] There
    4 min read
  • Check if an array can be split into K non-overlapping subarrays whose Bitwise AND values are equal
    Given an array arr[] of size N and a positive integer K, the task is to check if the array can be split into K non-overlapping and non-empty subarrays such that Bitwise AND of all the subarrays are equal. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { 3, 2,
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences