VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-subsets-distinct-elements/

⇱ Minimum Subsets with Distinct Elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Subsets with Distinct Elements

Last Updated : 7 Apr, 2026

You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicates. 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.

[Naive Solution] - Nested Loops - O(n^2) Time and O(1) Space

Let us take a look at few observations.

  • If all elements are distinct, we need to make only one subset.
  • If all elements are same, we need make n subsets.
  • If only one element appears twice, and all other are distinct, we need to make two subsets. For example for {1, 2, 3, 2, 4}, the two subsets are {1} and {1, 2, 3, 4}

Did you see any pattern?
We basically need to find the most frequent element in the array. The result is equal to the frequency of the most frequent element. Since we have to create a subset such that each element in a subset is unique that means that all the repeating elements should be kept in a different set. Hence the maximum number of subsets that we require is the frequency of the maximum time occurring element.

Ex -> { 1 , 2 , 1 , 2 , 3 , 3 , 2 , 2 }
here
Frequency of 1 -> 2
Frequency of 2 -> 4
Frequency of 3 -> 2

Since the frequency of 2 is maximum hence we need to have at least 4 subset to keep all the 2 in different subsets and rest of element can be occupied accordingly.

The naive approach involves using two nested loops: the outer loop picks each element, and the inner loop counts the frequency of the picked element. This method is straightforward but inefficient.


Output
3

[Better Approach] - Using Sorting - O(n log n) Time and O(1) Space

This method sorts the array first and then finds the maximum frequency by linearly traversing the sorted array. Sorting brings similar elements next to each other, making frequency counting easier.


Output
3

[Expected Approach] - Using Hashing - O(n) Time and O(n) Space

Using a hash table, this approach stores each element's frequency and then finds the element with the maximum frequency.


Output
3
Comment
Article Tags: