Minimum number of distinct elements present in a K-length subsequence in an array
Last Updated :
30 Jan, 2023
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 = 4
Output: 2
Explanation: The subsequence of length 4 containing minimum number of distinct elements is {3, 3, 3, 4}, consisting of 2 distinct elements, i.e. {3, 4}.
Input: A = {3, 1, 3, 2, 3, 4, 5, 4}, K = 5
Output: 2
Explanation: The subsequence of length 5 containing minimum number of distinct elements is {3, 3, 3, 4, 4}, consisting of 2 distinct elements, i.e. {3, 4}.
Naive Approach: The simplest approach is to generate all subsequences of length K and for each subsequence, find the number of distinct elements present in them. Finally, print the minimum number of distinct elements present.
Time Complexity: O(K * NK)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized using Hashing. Follow the steps below to solve the problem:
- Store the frequencies of all elements in the given array, A[] in a HashMap, say M.
- Traverse the hashmap, M and push the frequencies in another array, say V.
- Sort the array V in decreasing order.
- Initialize two variables, cnt and len as 0, to store the required result and the length of the subsequence thus formed.
- Traverse the array V[] using a variable, say i
- If the value of len ? K, then break out of the loop.
- Otherwise, increment the value of len by V[i] and cnt by 1.
- After completing the above steps, print the value of cnt as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the minimum number
// of distinct elements present in any
// subsequence of length K of the given array
void findMinimumDistinct(int A[], int N, int K)
{
// Stores the frequency
// of each array element
unordered_map<int, int> mp;
// Traverse the array
for (int i = 0; i < N; i++)
// Update frequency
// of array elements
mp[A[i]]++;
// Store the required result
int count = 0;
// Store the length of the
// required subsequence
int len = 0;
// Store the frequencies
// in decreasing order
vector<int> counts;
// Traverse the map
for (auto i : mp)
// Push the frequencies
// into the HashMap
counts.push_back(i.second);
// Sort the array in decreasing order
sort(counts.begin(), counts.end(),
greater<int>());
// Add the elements into the subsequence
// starting from one with highest frequency
for (int i = 0; i < counts.size(); i++) {
// If length of subsequence is >= k
if (len >= K)
break;
len += counts[i];
count++;
}
// Print the result
cout << count;
}
// Driver Code
int main()
{
int A[] = { 3, 1, 3, 2, 3, 4, 5, 4 };
int K = 4;
// Store the size of the array
int N = sizeof(A) / sizeof(A[0]);
// Function Call to count minimum
// number of distinct elements
// present in a K-length subsequence
findMinimumDistinct(A, N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count the minimum number
// of distinct elements present in any
// subsequence of length K of the given array
static void findMinimumDistinct(int A[], int N, int K)
{
// Stores the frequency
// of each array element
Map<Integer, Integer> mp = new HashMap<>();
// Traverse the array
for(int i = 0; i < N; i++)
// Update frequency
// of array elements
mp.put(A[i], mp.getOrDefault(A[i], 0) + 1);
// Store the required result
int count = 0;
// Store the length of the
// required subsequence
int len = 0;
// Store the frequencies
// in decreasing order
ArrayList<Integer> counts = new ArrayList<>();
// Traverse the map
for(Map.Entry<Integer, Integer> i : mp.entrySet())
// Push the frequencies
// into the HashMap
counts.add(i.getValue());
// Sort the array in decreasing order
Collections.sort(counts, (a, b) -> b - a);
// Add the elements into the subsequence
// starting from one with highest frequency
for(int i = 0; i < counts.size(); i++)
{
// If length of subsequence is >= k
if (len >= K)
break;
len += counts.get(i);
count++;
}
// Print the result
System.out.print(count);
}
// Driver code
public static void main(String[] args)
{
int A[] = { 3, 1, 3, 2, 3, 4, 5, 4 };
int K = 4;
// Store the size of the array
int N = A.length;
// Function Call to count minimum
// number of distinct elements
// present in a K-length subsequence
findMinimumDistinct(A, N, K);
}
}
// This code is contributed by offbeat
Python3
# Python3 program for the above approach
from collections import Counter
# Function to count the minimum number
# of distinct elements present in any
# subsequence of length K of the given array
def findMinimumDistinct(A, N, K):
# Stores the frequency
# of each array element
mp = Counter(A)
# Store the required result
count = 0
# Store the length of the
# required subsequence
length = 0
# Store the frequencies
# in decreasing order
counts = []
# Traverse the map
for i in mp:
# Push the frequencies
# into the HashMap
counts.append(mp[i])
# Sort the array in decreasing order
counts = sorted(counts)
counts.reverse()
# Add the elements into the subsequence
# starting from one with highest frequency
for i in range(len(counts)):
# If length of subsequence is >= k
if (length >= K):
break
length += counts[i]
count += 1
# Print the result
print(count)
# Driver Code
A = [3, 1, 3, 2, 3, 4, 5, 4]
K = 4
# Store the size of the array
N = len(A)
# Function Call to count minimum
# number of distinct elements
# present in a K-length subsequence
findMinimumDistinct(A, N, K)
# This code is contributed by sudhanshugupta2019a
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int[] A = new int[] { 3, 1, 3, 2, 3, 4, 5, 4 };
int K = 4;
int N = A.Length;
Console.WriteLine(FindMinimumDistinct(A, N, K));
}
static int FindMinimumDistinct(int[] A, int N, int K)
{
Dictionary<int, int> mp = new Dictionary<int, int>();
foreach (var item in A)
{
if (mp.ContainsKey(item))
mp[item]++;
else
mp[item] = 1;
}
int count = 0;
int length = 0;
List<int> counts = new List<int>();
foreach (var item in mp)
counts.Add(item.Value);
counts.Sort();
counts.Reverse();
for (int i = 0; i < counts.Count; i++)
{
if (length >= K)
break;
length += counts[i];
count++;
}
return count;
}
}
// This code is contributed by shivamsharma215
JavaScript
<script>
// JavaScript program for the above approach
// Function to count the minimum number
// of distinct elements present in any
// subsequence of length K of the given array
function findMinimumDistinct(A, N, K)
{
// Stores the frequency
// of each array element
let mp = new Map();
// Traverse the array
for (let i = 0; i < N; i++){
// Update frequency
// of array elements
if(mp.has(A[i])){
mp.set(A[i],mp.get(A[i])+1)
}
else mp.set(A[i],1)
}
// Store the required result
let count = 0;
// Store the length of the
// required subsequence
let len = 0;
// Store the frequencies
// in decreasing order
let counts = [];
// Traverse the map
for (let [i,j] of mp)
// Push the frequencies
// into the HashMap
counts.push(j);
// Sort the array in decreasing order
counts.sort((a,b)=>b-a);
// Add the elements into the subsequence
// starting from one with highest frequency
for (let i = 0; i < counts.length; i++) {
// If length of subsequence is >= k
if (len >= K)
break;
len += counts[i];
count++;
}
// Print the result
document.write(count);
}
// Driver Code
let A = [ 3, 1, 3, 2, 3, 4, 5, 4 ];
let K = 4;
// Store the size of the array
let N = A.length;
// Function Call to count minimum
// number of distinct elements
// present in a K-length subsequence
findMinimumDistinct(A, N, K);
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(N*log(N))
Auxiliary Space: O(N)
Similar Reads
Maximize count of distinct elements in a subsequence of size K in given array Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers. Example: Input: arr[]={1, 1, 2, 2}, K=3Output: 2Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are
4 min read
Divide the array into minimum number of sub-arrays having unique elements Given an array arr. The task is to divide the array into the minimum number of subarrays containing unique elements and return the count of such subarrays. Note: An array element cannot be present in more than one subarray.Examples : Input : arr[] = {1, 2, 1, 1, 2, 3}Output : 3Explanation : The suba
8 min read
Count of subsequences of length atmost K containing distinct prime elements Given an array arr of length N and an integer K, the task is to count the number of possible subsequences of length at most K which contains distinct prime elements from the array. Examples: Input: arr[] = {1, 2, 2, 3, 3, 4, 5}, N = 7, K = 3 Output: 18 Explanation: {}, {2}, {2}, {3}, {3}, {5}, {2, 3
12 min read
Minimize the number of strictly increasing subsequences in an array | Set 2 Given an array arr[] of size N, the task is to print the minimum possible count of strictly increasing subsequences present in the array. Note: It is possible to swap the pairs of array elements. Examples: Input: arr[] = {2, 1, 2, 1, 4, 3}Output: 2Explanation: Sorting the array modifies the array to
6 min read
Count of subsequences having maximum distinct elements Given an arr of size n. The problem is to count all the subsequences having maximum number of distinct elements. Examples: Input : arr[] = {4, 7, 6, 7} Output : 2 The indexes for the subsequences are: {0, 1, 2} - Subsequence is {4, 7, 6} and {0, 2, 3} - Subsequence is {4, 6, 7} Input : arr[] = {9, 6
5 min read