CC-15 : Reduce input array to half.
Description:
Given an array of integers, find the minimum number of integers to remove to reduce the array size to half. When an integer is removed, all its duplicates are also removed from array. So to have minimum numbers of distinct integers that are removed, remove the integers with duplicates first.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Nums : 3,3,3,4,7,9,3,4,10,15,11,1,1,7 |
Minimum distinct Numbers to be removed to reduce size to half: 3 |
Pseudocode:
| Array of integers is received as input parameter. |
| Initialize a HashMap named freq which we will use to count the frequency of occurrence of integersx in the input array. |
| Iterate though nums from index 0 to index chars.length-1:
Check if hashMap already contains nums[idx]. If already present, extract the frequency of the nums[idx] from hashMap. Increment the frequency by 1 and put nums[idx] and the updated frequency back into to the HashMap.
|
| Initialize a PriorityQueue instance named maxHeap. |
| Iterate through values of hashMap freq:
Add the current value (frequency) to heap.
|
| Initialize variable removedNumsCnt to 0; this is used to count how many count of integers we have removed from the array(including duplicate nums). |
| Initialize variable removedNumsUnique to 0; this is used to count how many count of integers we have removed from the array(distinct nums). |
| Initialize variable named half to nums.length/2. |
| While (removedNumsCnt < half):
Remove frequency value from top of MaxHeap.
Add above frequency to removedNumsCnt.
Increment removedNumsUnique by 1.
|
| Return removedNumsUnique as now it contains the minimum number of integers to remove to reduce the array size to half. |
Code:
public int reduceArrToHalf(int[] nums) {
HashMap<Integer,Integer> freq=new HashMap<Integer,Integer>();
for (int idx=0; idx < nums.length; idx++) {
int currFreq=freq.getOrDefault(nums[idx],0);
freq.put(nums[idx], currFreq+1);
}
PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(Collections.reverseOrder());
Iterator<Integer> itr=freq.values().iterator();
while (itr.hasNext()) {
maxHeap.add((Integer)itr.next());
}
int removedNumsCnt=0;
int removedNumsUnique=0;
int half=nums.length/2;
while(removedNumsCnt < half) {
int numsBeingRemoved=maxHeap.remove();
removedNumsCnt+=numsBeingRemoved;
removedNumsUnique++;
}
return removedNumsUnique;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |