Open In App
Related Articles

Count minimum number of subsets (or subsequences) with consecutive numbers

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given an array of distinct positive numbers, the task is to calculate the number of subsets (or subsequences) from the array such that each subset contains consecutive numbers.

Examples: 

Input :  arr[] = {100, 56, 5, 6, 102, 58, 
101, 57, 7, 103, 59}
Output : 3
{5, 6, 7}, { 56, 57, 58, 59}, {100, 101, 102, 103}
are 3 subset in which numbers are consecutive.
Input : arr[] = {10, 100, 105}
Output : 3
{10}, {100} and {105} are 3 subset in which
numbers are consecutive.

The idea is to sort the array and traverse the sorted array to count the number of such subsets. To count the number of such subsets, we need to count the consecutive numbers such that the difference between them is not equal to one.

Following is the algorithm for the finding number of subset containing consecutive numbers: 

1. Sort the array arr[ ] and count = 1.
2. Traverse the sorted array and for each element arr[i].
If arr[i] + 1 != arr[i+1],
then increment the count by one.
3. Return the count.

Below is the implementation of this approach :  

C++

// C++ program to find number of subset containing
// consecutive numbers
#include <bits/stdc++.h>
using namespace std;
 
// Returns count of subsets with consecutive numbers
int numofsubset(int arr[], int n)
{
    // Sort the array so that elements which are
    // consecutive in nature became consecutive
    // in the array.
    sort(arr, arr + n);
 
    int count = 1; // Initialize result
    for (int i = 0; i < n - 1; i++) {
        // Check if there is beginning of another
        // subset of consecutive number
        if (arr[i] + 1 != arr[i + 1])
            count++;
    }
 
    return count;
}
 
// Driven Program
int main()
{
    int arr[] = { 100, 56, 5, 6, 102, 58, 101,
                  57, 7, 103, 59 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << numofsubset(arr, n) << endl;
    return 0;
}

                    

Java

// Java program to find number of subset
// containing consecutive numbers
import java.util.*;
class GFG {
 
    // Returns count of subsets with consecutive numbers
    static int numofsubset(int arr[], int n)
    {
        // Sort the array so that elements
        // which are consecutive in nature
        // became consecutive in the array.
        Arrays.sort(arr);
 
        // Initialize result
        int count = 1;
        for (int i = 0; i < n - 1; i++) {
            // Check if there is beginning
            // of another subset of
            // consecutive number
            if (arr[i] + 1 != arr[i + 1])
                count++;
        }
 
        return count;
    }
 
    // Driven Program
    public static void main(String[] args)
    {
        int arr[] = { 100, 56, 5, 6, 102, 58, 101,
                      57, 7, 103, 59 };
        int n = arr.length;
        System.out.println(numofsubset(arr, n));
    }
}
 
// This code is contributed by prerna saini.

                    

Python3

# Python program to find number of subset containing
# consecutive numbers
def numofsubset(arr, n):
 
  # Sort the array so that elements which are consecutive
  # in nature became consecutive in the array.
  x = sorted(arr)
  
  count = 1
  
  for i in range(0, n-1):
 
    # Check if there is beginning of another subset of
    # consecutive number
    if (x[i] + 1 != x[i + 1]):
      count = count + 1
  
  return count
 
# Driven Program
arr = [ 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 ]
n = len(arr)
print (numofsubset(arr, n))
 
# This code is contributed by Afzal Ansari.

                    

C#

// C# program to find number of subset
// containing consecutive numbers
using System;
 
class GFG {
 
    // Returns count of subsets with
    // consecutive numbers
    static int numofsubset(int[] arr, int n)
    {
        // Sort the array so that elements
        // which are consecutive in nature
        // became consecutive in the array.
        Array.Sort(arr);
 
        // Initialize result
        int count = 1;
        for (int i = 0; i < n - 1; i++) {
             
            // Check if there is beginning
            // of another subset of
            // consecutive number
            if (arr[i] + 1 != arr[i + 1])
                count++;
        }
 
        return count;
    }
 
    // Driven Program
    public static void Main()
    {
        int[] arr = { 100, 56, 5, 6, 102, 58, 101,
                                 57, 7, 103, 59 };
        int n = arr.Length;
        Console.WriteLine(numofsubset(arr, n));
    }
}
 
// This code is contributed by vt_m.

                    

Javascript

<script>
// javascript program to find number of subset
// containing consecutive numbers
 
    // Returns count of subsets with consecutive numbers
    function numofsubset(arr , n) {
        // Sort the array so that elements
        // which are consecutive in nature
        // became consecutive in the array.
        arr.sort((a,b)=>a-b);
 
        // Initialize result
        var count = 1;
        for (i = 0; i < n - 1; i++) {
            // Check if there is beginning
            // of another subset of
            // consecutive number
            if (arr[i] + 1 != arr[i + 1])
                count++;
        }
 
        return count;
    }
 
    // Driven Program
     
        var arr = [ 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 ];
        var n = arr.length;
        document.write(numofsubset(arr, n));
 
// This code contributed by Rajput-Ji
</script>

                    

PHP

<?php
// PHP program to find number
// of subset containing
// consecutive numbers
 
// Returns count of subsets
// with consecutive numbers
function numofsubset( $arr, $n)
{
     
    // Sort the array so that
    // elements which are
    // consecutive in nature
    // became consecutive
    // in the array.
    sort($arr);
 
    // Initialize result
    $count = 1;
    for ($i = 0; $i < $n - 1; $i++)
    {
         
        // Check if there is
        // beginning of another
        // subset of consecutive
        // number
        if ($arr[$i] + 1 != $arr[$i + 1])
            $count++;
    }
 
    return $count;
}
 
    // Driver Code
    $arr = array(100, 56, 5, 6, 102, 58, 101,
                 57, 7, 103, 59 );
    $n = sizeof($arr);
    echo numofsubset($arr, $n);
     
// This code is contributed by Anuj_67
?>

                    

Output
3







Time Complexity : O(nlogn)

Auxiliary Space :O(1) , since no extra space required.

Using Hashing:

Follow the steps below to implement the approach:

  1. Create an unordered set to keep track of the presence of each element in the array.
  2. Iterate through the array and add each element to the set.
  3. Iterate through the array again and for each element, check if its previous element is present in the subset. If not, start a new subset and add all consecutive elements to it.
  4. Increment the count variable for each new subset.
  5. Return the count variable which represents the minimum number of subsets required.

Below is the implementation of the above approach:

C++

// C++ code to implement hashing approach
#include <bits/stdc++.h>
using namespace std;
 
int countSubsets(int arr[], int n) {
    unordered_set<int> s;
    int count = 0;
    // iterate through the array and add each element to the set
    for(int i = 0; i < n; i++) {
        s.insert(arr[i]);
    }
    // iterate through the array again and for each element, check if it is the starting element of a subset
    for(int i = 0; i < n; i++) {
        if(s.find(arr[i]-1) == s.end()) {
            int j = arr[i];
            // count the number of consecutive elements and add them to the set
            while(s.find(j) != s.end()) {
                j++;
            }
            count++;
        }
    }
    return count;
}
// driver code
int main() {
    int arr[] = {100, 56, 5, 6, 102, 58, 101, 57, 7, 103};
    int n = sizeof(arr)/sizeof(arr[0]);
    int subsets = countSubsets(arr, n);
    cout  << subsets << endl;
    return 0;
}
// This code is contributed by Veerendra_Singh_Rajpoot

                    

Java

// Java code to implement hashing approach
import java.util.HashSet;
 
public class GFG {
    public static int countSubsets(int[] arr, int n) {
        HashSet<Integer> set = new HashSet<>();
        int count = 0;
        // Iterate through the array and add each element to the set
        for (int i = 0; i < n; i++) {
            set.add(arr[i]);
        }
        // Iterate through the array again and for each element,
       // check if it is the starting element of a subset
        for (int i = 0; i < n; i++) {
            if (!set.contains(arr[i] - 1)) {
                int j = arr[i];
                // Count the number of consecutive elements
               // and add them to the set
                while (set.contains(j)) {
                    j++;
                }
                count++;
            }
        }
        return count;
    }
 
    // Driver code
    public static void main(String[] args) {
        int[] arr = {100, 56, 5, 6, 102, 58, 101, 57, 7, 103};
        int n = arr.length;
        int subsets = countSubsets(arr, n);
        System.out.println(subsets);
    }
}

                    

Python3

def count_subsets(arr, n):
    s = set()
    count = 0
     
    # Iterate through the array and add each element to the set
    for i in range(n):
        s.add(arr[i])
     
    # Iterate through the array again and for each element, check if it is the starting element of a subset
    for i in range(n):
        if (arr[i] - 1) not in s:
            j = arr[i]
            # Count the number of consecutive elements and add them to the set
            while j in s:
                j += 1
            count += 1
             
    return count
 
# Driver code
if __name__ == "__main__":
    arr = [100, 56, 5, 6, 102, 58, 101, 57, 7, 103]
    n = len(arr)
    subsets = count_subsets(arr, n)
    print(subsets)
# This code is contributed by akshitaguprzj3

                    

C#

using System;
using System.Collections.Generic;
 
class SubsetsCount
{
    static int CountSubsets(int[] arr, int n)
    {
        // Use HashSet for efficient lookup
        HashSet<int> set = new HashSet<int>();
        int count = 0;
 
        // Iterate through the array and add each element to the set
        for (int i = 0; i < n; i++)
        {
            set.Add(arr[i]);
        }
 
        // Iterate through the array again and for each element, check if it is the starting
        // element of a subset
        for (int i = 0; i < n; i++)
        {
            if (!set.Contains(arr[i] - 1))
            {
                int j = arr[i];
 
                // Count the number of consecutive elements and add them to the set
                while (set.Contains(j))
                {
                    j++;
                }
 
                count++;
            }
        }
 
        return count;
    }
 
    // Driver code
    static void Main()
    {
        int[] arr = { 100, 56, 5, 6, 102, 58, 101, 57, 7, 103 };
        int n = arr.Length;
 
        // Function call
        int subsets = CountSubsets(arr, n);
        Console.WriteLine(subsets);
    }
}

                    

Javascript

// Javascript code to implement hashing approach
function countSubsets(arr) {
    let s = new Set();
    let count = 0;
    // iterate through the array and add each element to the set
    for(let i = 0; i < arr.length; i++) {
        s.add(arr[i]);
    }
    // iterate through the array again and for each element,
    // check if it is the starting element of a subset
    for(let i = 0; i < arr.length; i++) {
        if(!s.has(arr[i]-1)) {
            let j = arr[i];
            // count the number of consecutive elements and
            // add them to the set
            while(s.has(j)) {
                j++;
            }
            count++;
        }
    }
    return count;
}
// driver code
let arr = [100, 56, 5, 6, 102, 58, 101, 57, 7, 103];
let subsets = countSubsets(arr);
console.log(subsets);

                    

Output
3







Time Complexity : O(n) , where n is the number of element in the array

Auxiliary Space :O(n) , As we need to store all the element in the Unordered set.

 



Last Updated : 07 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads