Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Minimum number of subsets with distinct elements using Counter
Next article icon

Python | Minimum number of subsets with distinct elements using Counter

Last Updated : 27 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
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).


Next Article
Python | Minimum number of subsets with distinct elements using Counter

S

Shashank Mishra
Improve
Article Tags :
  • Python
  • python-dict
  • python-set
  • Python dictionary-programs
  • Python set-programs
Practice Tags :
  • python
  • python-dict
  • python-set

Similar Reads

    Python | Find the number of unique subsets with given sum in array
    Given an array and a sum, find the count of unique subsets with each subset's sum equal to the given sum value. Examples: Input : 4 12 5 9 12 9 Output : 2 (subsets will be [4, 5] and [9]) Input : 1 2 3 4 5 10 Output : 3 We will use dynamic programming to solve this problem and this solution has time
    2 min read
    Minimum number of distinct elements present in a K-length subsequence in an array
    Given an array A[] consisting of N integers and an integer K, the task is to count the minimum number of distinct elements present in a subsequence of length K of the given array, A. Examples: Input: A = {3, 1, 3, 2, 3, 4, 5, 4}, K = 4Output: 2Explanation: The subsequence of length 4 containing mini
    7 min read
    Count distinct elements in an array in Python
    Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
    2 min read
    Count the number of Unique Characters in a String in Python
    We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8.Using setSet in Python is an unordered collection of unique elements automatically removing du
    2 min read
    Count frequencies of all elements in array in Python using collections module
    Given an unsorted array of n integers which can contains n integers. Count frequency of all elements that are present in array. Examples: Input : arr[] = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5] Output : 1 -> 4 2 -> 4 3 -> 2 4 -> 1 5 -> 2 This problem can be solved in many ways, refer
    2 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