Python
# Python program to find number of subset containing
# consecutive numbers using Hash Map in O(n)
def countSubsets(arr):
# Create a set from the list
s = set(arr)
count = 0
for x in arr:
# Check for the start of a new subset
if (x - 1) not in s:
j = x
# Count consecutive elements in the set
while j in s:
j += 1
count += 1
return count
arr = [100, 56, 5, 6, 102, 58, 101, 57, 7, 103]
print(countSubsets(arr))
Java
// Java program to find number of subset containing
// consecutive numbers using Hash Map in O(n)
import java.util.*;
class GfG {
static int countSubsets(int[] arr) {
// Create a HashSet from the array
Set<Integer> s = new HashSet<>();
for(int num : arr){
s.add(num);
}
int count = 0;
for(int x : arr){
// Check for the start of a new subset
if(!s.contains(x - 1)){
int j = x;
// Count consecutive elements in the set
while(s.contains(j)){
j++;
}
count++;
}
}
return count;
}
public static void main(String[] args){
int[] arr = {100, 56, 5, 6, 102, 58, 101, 57, 7, 103};
System.out.println(countSubsets(arr));
}
}
C#
// C# program to find number of subset containing
// consecutive numbers using Hash Map in O(n)
using System;
using System.Collections.Generic;
class GfG {
static int countSubsets(List<int> arr) {
// Create a HashSet from the list
HashSet<int> s = new HashSet<int>(arr);
int count = 0;
foreach(int x in arr){
// Check for the start of a new subset
if(!s.Contains(x - 1)){
int j = x;
// Count consecutive elements in the set
while(s.Contains(j)){
j++;
}
count++;
}
}
return count;
}
static void Main(){
List<int> arr = new List<int>{100, 56, 5, 6, 102, 58, 101, 57, 7, 103};
Console.WriteLine(countSubsets(arr));
}
}
JavaScript
// JavaScript program to find number of subset containing
// consecutive numbers using Hash Map in O(n)
function countSubsets(arr) {
// Create a Set from the array
let s = new Set(arr);
let count = 0;
for(let x of arr){
// Check for the start of a new subset
if(!s.has(x - 1)){
let j = x;
// Count consecutive elements in the set
while(s.has(j)){
j++;
}
count++;
}
}
return count;
}
let arr = [100, 56, 5, 6, 102, 58, 101, 57, 7, 103];
console.log(countSubsets(arr));