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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Check if an array can be split into 3 subsequences of equal sum or not
Next article icon

Check if an array can be split into subsets of K consecutive elements

Last Updated : 17 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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}, {2, 3, 4} and {6, 7, 8} such that each subset consists of 3 consecutive elements.

Input: arr[] = [1, 2, 3, 4, 5], K = 4 
Output: false 
Explanation: 
The given array of length 5 cannot be split into subsets of 4. 
 

Approach 
Follow the steps to solve the problem: 

Instead of a HashMap, you can use an array or another data structure to store the frequencies of array elements. This can lead to better performance since direct array access is typically faster than hashmap lookups.

Instead of traversing the entire HashMap, you can optimize the traversal by iterating over the array directly and checking for consecutive elements.

The description mentions grouping elements with their next (K – 1) consecutive elements. It’s important to clarify whether these consecutive elements are strictly consecutive or if there can be gaps between them.

  • Sort the array to simplify consecutive element checking.
  • Iterate through the sorted array and check if each element can be grouped with the next (K – 1) elements.
  • If any element cannot be grouped into a subset of K consecutive elements, return False. Otherwise, return True.

Below is the implementation of the above approach:

C++
#include <iostream> #include <algorithm> #include <vector> using namespace std;  bool canSplitArray(vector<int>& arr, int K) {     int n = arr.size();          // Sort the array to simplify consecutive element checking     sort(arr.begin(), arr.end());          // Iterate through the sorted array and check for consecutive elements     for (int i = 0; i < n - K + 1; i++) {         // Check if each element can be grouped with the next (K - 1) elements         if (arr[i + K - 1] - arr[i] != K - 1) {             return false;         }     }          return true; }  int main() {     vector<int> arr1 = {1, 2, 3, 6, 2, 3, 4, 7, 8};     int K1 = 3;     cout << "Output for arr1: " << boolalpha << canSplitArray(arr1, K1) << endl; // Output: true          vector<int> arr2 = {1, 2, 3, 4, 5};     int K2 = 4;     cout << "Output for arr2: " << boolalpha << canSplitArray(arr2, K2) << endl; // Output: false          return 0; } 
Java
import java.util.Arrays;  public class SplitArrayIntoSubsets {      public static boolean canSplitArray(int[] arr, int K) {         int n = arr.length;                  // Sort the array to simplify consecutive element checking         Arrays.sort(arr);                  // Iterate through the sorted array and check for consecutive elements         for (int i = 0; i < n - K + 1; i++) {             // Check if each element can be grouped with the next (K - 1) elements             if (arr[i + K - 1] - arr[i] != K - 1) {                 return false;             }         }                  return true;     }      public static void main(String[] args) {         int[] arr1 = {1, 2, 3, 6, 2, 3, 4, 7, 8};         int K1 = 3;         System.out.println("Output for arr1: " + canSplitArray(arr1, K1)); // Output: true                  int[] arr2 = {1, 2, 3, 4, 5};         int K2 = 4;         System.out.println("Output for arr2: " + canSplitArray(arr2, K2)); // Output: false     } } 
Python3
def can_split_array(arr, K):     arr.sort()     for i in range(len(arr) - K + 1):         if arr[i + K - 1] - arr[i] != K - 1:             return False     return True  arr1 = [1, 2, 3, 6, 2, 3, 4, 7, 8] K1 = 3 print("Output for arr1:", can_split_array(arr1, K1)) # Output: True  arr2 = [1, 2, 3, 4, 5] K2 = 4 print("Output for arr2:", can_split_array(arr2, K2)) # Output: False 
C#
using System; using System.Linq;  public class Program {     public static bool CanSplitArray(int[] arr, int K)     {         Array.Sort(arr);         for (int i = 0; i < arr.Length - K + 1; i++)         {             if (arr[i + K - 1] - arr[i] != K - 1)             {                 return false;             }         }         return true;     }      public static void Main(string[] args)     {         int[] arr1 = { 1, 2, 3, 6, 2, 3, 4, 7, 8 };         int K1 = 3;         Console.WriteLine("Output for arr1: " + CanSplitArray(arr1, K1)); // Output: true                  int[] arr2 = { 1, 2, 3, 4, 5 };         int K2 = 4;         Console.WriteLine("Output for arr2: " + CanSplitArray(arr2, K2)); // Output: false     } } 
JavaScript
function canSplitArray(arr, K) {     arr.sort((a, b) => a - b);     for (let i = 0; i < arr.length - K + 1; i++) {         if (arr[i + K - 1] - arr[i] !== K - 1) {             return false;         }     }     return true; }  let arr1 = [1, 2, 3, 6, 2, 3, 4, 7, 8]; let K1 = 3; console.log("Output for arr1:", canSplitArray(arr1, K1)); // Output: true  let arr2 = [1, 2, 3, 4, 5]; let K2 = 4; console.log("Output for arr2:", canSplitArray(arr2, K2)); // Output: false 

Output
True

Time Complexity: O(N*log(N))

Auxiliary Space: O(N)
 



Next Article
Check if an array can be split into 3 subsequences of equal sum or not
author
coder001
Improve
Article Tags :
  • Arrays
  • Data Structures
  • DSA
  • Hash
  • Searching
  • Sorting
  • cpp-map
  • frequency-counting
  • subset
Practice Tags :
  • Arrays
  • Data Structures
  • Hash
  • Searching
  • Sorting
  • subset

Similar Reads

  • Check if an array can be split into subarrays with GCD exceeding K
    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 s
    5 min read
  • Check if an array can be split into 3 subsequences of equal sum or not
    Given an array arr[] having N integers. The task is to determine if the array can be partitioned into 3 subsequences of an equal sum or not. If yes then print “Yes”. Otherwise, print “No”. Examples: Input: arr[] = {1, 1, 1}Output: YesExplanation:Here array can be partition into 3 equal sum. {1} Inpu
    15+ min read
  • Check if N can be divided into K consecutive elements with a sum equal to N
    Given an integer N, our task is to check if N can be divided into K consecutive elements with a sum equal to N. Print -1 if it is not possible to divide in this manner, otherwise print the value K.Examples: Input: N = 12 Output: 3 Explanation: The integer N = 12 can be divided into 3 consecutive ele
    5 min read
  • Maximise the size of consecutive element subsets in an array
    Given an integer array and an integer k. The array elements denote positions of points on a 1-D number line, find the maximum size of the subset of points that can have consecutive values of points which can be formed by placing another k points on the number line. Note that all coordinates should b
    12 min read
  • Check if all array elements can be converted to K using given operations
    Given an integer array arr of size N and an integer K, the task is to make all elements of the array equal to K using the following operations: Choose an arbitrary subarray [l....r] of the input arrayReplace all values of this subarray equal to the [((r - l) + 2) / 2]th value in sorted subarray [l..
    9 min read
  • Check if given Array can be divided into subsequences of K increasing consecutive integers
    Given an array arr[] of N integers and a positive integer K, the task is to check if it is possible to divide the array into increasing subsequences of K consecutive integers such each element can contribute in only a single subsequence. Example: Input: arr[] = {1, 2, 1, 3, 2, 3}, K = 3Output: YesEx
    11 min read
  • Check if an array can be split into K consecutive non-overlapping subarrays of length M consisting of single distinct element
    Given two integers M and K and an array arr[] consisting of N positive integers, the task is to check if the array can be split into K consecutive non-overlapping subarrays of length M such that each subarray consists of a single distinct element. If found to be true, then print "Yes". Otherwise, pr
    8 min read
  • Check if Array can be divided into K groups of size C and all elements of group are distinct
    Given an array A[] of size N, and two integers K and C, the task is to check if all the elements of the array can be grouped into K groups such that each group has at most C elements and all the elements of a group are distinct. Examples: Input: N=6, A=[1, 2, 1, 2, 3, 4], K = 2, C=3Output: PossibleE
    10 min read
  • Check if given Array can be made a binary Array with K consecutive 1s
    Given an array A[] of size N and an integer K. Each element of the array is either 0, 1 or 2. The task is to check if the array can be converted into a binary array (elements will be either 0 or 1) by replacing every element equal to 2 with either 0 or 1, such that there are only K occurrences of 1,
    11 min read
  • Query to check if a range is made up of consecutive elements
    Given an array of n non-consecutive integers and Q queries, the task is to check whether for the given range l and r, the elements are consecutive or not.Examples: Input: arr = { 2, 4, 3, 7, 6, 1}, Q = { (1, 3), (3, 5), (5, 6) } Output: Yes, No, No Explanation: Array elements from (1, 3) = {2, 4, 3}
    15+ 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