Open In App

Python | Minimum number of subsets with distinct elements using Counter

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible. Examples:

Input : arr[] = {1, 2, 3, 4}
Output :1
Explanation : A single subset can contains all 
values and all values are distinct

Input : arr[] = {1, 2, 3, 3}
Output : 2
Explanation : We need to create two subsets
{1, 2, 3} and {3} [or {1, 3} and {2, 3}] such
that both subsets have distinct elements.

We have existing solution for this problem please refer Minimum number of subsets with distinct elements link. We will solve this problem quickly in python using Counter(iterable) method. Approach is very simple, calculate frequency of each element in array and print value of maximum frequency because we want each subset to be different and we have to put any repeated element in different subset, so to get minimum number of subset we should have at least maximum frequency number of subsets

Python3




# Python program to find Minimum number of
# subsets with distinct elements using Counter
 
# function to find Minimum number of subsets
# with distinct elements
from collections import Counter
 
def minSubsets(input):
 
     # calculate frequency of each element
     freqDict = Counter(input)
 
     # get list of all frequency values
     # print maximum from it
     print (max(freqDict.values()))
 
# Driver program
if __name__ == "__main__":
    input = [1, 2, 3, 3]
    minSubsets(input)


Output

2

Approach#2: Using Counter and itertools.combinations()

We use Counter to count the frequency of each element in the input array. Then, we calculate the number of distinct elements in the array. If the number of distinct elements is equal to the length of the array, we return 1, as all elements are distinct and can be put in a single subset. Otherwise, we try to create subsets of increasing size, until we can create a subset with all the distinct elements. We check if the subset contains only distinct elements and the sum of frequencies of all elements in the subset is greater than or equal to the size of the subset.

Algorithm

1. Calculate the frequency of each element in the input array using Counter.
2. Calculate the number of distinct elements in the array using set() and len().
3. If the number of distinct elements is equal to the length of the array, return 1. Otherwise, try to create subsets of increasing size from 1 to the number of distinct elements.
4. For each subset size, generate all possible subsets using combinations() from itertools.
5. For each subset, check if the subset contains only distinct elements and the sum of frequencies of all elements in the subset is greater than or equal to the size of the subset.
6. If such a subset is found, return its size.
7. If no subset is found for any size, return -1.

Python3




from collections import Counter
from itertools import combinations
 
def count_min_subsets(arr):
    freq = Counter(arr)
    num_distinct = len(set(arr))
    if num_distinct == len(arr):
        return 1
    else:
        for i in range(1, num_distinct+1):
            for subset in combinations(freq.keys(), i):
                if len(set(subset)) == i:
                    if sum([freq[k] for k in subset]) >= i:
                        return i+1
 
arr=[1, 2, 3, 4]
print(count_min_subsets(arr))


Output

1

Time Complexity: O(2^n * n), where n is the number of distinct elements in the array. The combinations() function generates all possible subsets of each size, and for each subset, we need to check if it contains only distinct elements and if the sum of frequencies is greater than or equal to the size of the subset. Therefore, the time complexity is exponential in the number of distinct elements.

Space Complexity: O(n), where n is the number of distinct elements in the array. We use a Counter to store the frequency of each element in the array, which requires O(n) space. The combinations() function also generates subsets of size up to n, so the space complexity is also O(n).



Similar Reads

Python - Counter.items(), Counter.keys() and Counter.values()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-class that is used to count hashable objects. It imp
3 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Python | Counter Objects | elements()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-class that is used to count hashable objects. It im
5 min read
Python - Matrix elements Frequencies Counter
Sometimes, while working with python Matrix, we can have a problem in which we need to find frequencies of all elements in Matrix. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using Counter() + sum() + map() The combination of above methods can be used to perfo
5 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Anagram checking in Python using collections.Counter()
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input : str1 = “abcd”, str2 = “dabc” Output : True Input : str1 = “abcf”, str
2 min read
Create Word Counter app using Django
In this article, we are going to make a simple tool that counts a number of words in text using Django. Before diving into this topic you need to have some basic knowledge of Django. Refer to the below article to know about basics of Django. Django BasicsHow to Create a Basic Project using MVT in Django ? Now moving forward to make our wordcounter,
3 min read
Create a Counter App Using React, Tailwind and Django Framework
This article will guide you in creating a Counter using React and Tailwind with the Django Framework. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Counter in Python using the Django Framework. What is Counter App?The Counter app is a straightforward tool designed for easy
6 min read
Python dictionary, set and counter to check if frequencies can become same
Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str =
2 min read
Dictionary and counter in Python to find winner of election
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny",
3 min read