Check if an array can be reduced to at most length K by removal of distinct elements
Last Updated :
29 Jun, 2021
Given an array arr[] consisting of N positive integers and an integer K, the task is to check if it is possible to reduce the size of the array to at most K or not by removing a subset of the distinct array elements. If it is possible, then print “Yes”. Otherwise, print “No”.
Examples:
Input: arr[] = {2, 2, 2, 3}, K = 3
Output: Yes
Explanation:
By removing the subset {2, 3}, the array modifies to {2, 2} (Size = 2).
Input: arr[] = {1, 1, 1, 3}, K = 1
Output: No
Approach: The given problem can be solved by finding the number of distinct elements in the given array, say count. If the value of (N – count) is at most K, then print Yes. Otherwise, print No.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void maxCount( int arr[], int N, int K)
{
set< int > st;
for ( int i = 0; i < N; i++) {
st.insert(arr[i]);
}
if (N - st.size() <= K) {
cout << "Yes" ;
}
else
cout << "No" ;
}
int main()
{
int arr[] = { 2, 2, 2, 3 };
int K = 3;
int N = sizeof (arr) / sizeof (arr[0]);
maxCount(arr, N, K);
return 0;
}
|
Java
import java.util.HashSet;
public class GFG
{
static void maxCount( int arr[], int N, int K)
{
HashSet<Integer> st = new HashSet<>();
for ( int i = 0 ; i < N; i++) {
st.add(arr[i]);
}
if (N - st.size() <= K) {
System.out.println( "Yes" );
}
else
System.out.println( "No" );
}
public static void main(String[] args)
{
int arr[] = { 2 , 2 , 2 , 3 };
int K = 3 ;
int N = arr.length;
maxCount(arr, N, K);
}
}
|
Python3
def maxCount(arr, N, K):
st = set ()
for i in range (N):
st.add(arr[i])
if (N - len (st) < = K):
print ( "Yes" )
else :
print ( "No" )
if __name__ = = '__main__' :
arr = [ 2 , 2 , 2 , 3 ]
K = 3
N = len (arr)
maxCount(arr, N, K)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void maxCount( int [] arr, int N, int K)
{
HashSet< int > st = new HashSet< int >();
for ( int i = 0; i < N; i++)
{
st.Add(arr[i]);
}
if (N - st.Count <= K)
{
Console.Write( "Yes" );
}
else
Console.Write( "No" );
}
static public void Main()
{
int [] arr = { 2, 2, 2, 3 };
int K = 3;
int N = arr.Length;
maxCount(arr, N, K);
}
}
|
Javascript
<script>
function maxCount(arr, N, K) {
let st = new Set();
for (let i = 0; i < N; i++) {
st.add(arr[i]);
}
if (N - st.size <= K) {
document.write( "Yes" );
}
else
document.write( "No" );
}
let arr = [2, 2, 2, 3];
let K = 3;
let N = arr.length
maxCount(arr, N, K);
</script>
|
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...