Open In App

Remove minimum number of elements such that no common element exist in both array

Last Updated : 19 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays A[] and B[] consisting of n and m elements respectively. Find the minimum number of elements to remove from each array such that no common element exist in both.

Examples: 

Input : A[] = { 1, 2, 3, 4}
        B[] = { 2, 3, 4, 5, 8 }
Output : 3
We need to remove 2, 3 and 4 from any array.

Input : A[] = { 4, 2, 4, 4}
        B[] = { 4, 3 }
Output : 1
We need to remove 4 from B[]

Input : A[] = { 1, 2, 3, 4 }
        B[] = { 5, 6, 7 }
Output : 0
There is no common element in both.

Count occurrence of each number in both arrays. If there is a number in both array remove number from array in which it appears less number of times add it to the result. 

Implementation:

C++





Java




// JAVA Code to Remove minimum number of elements
// such that no common element exist in both array
import java.util.*;
 
class GFG {
     
    // To find no elements to remove
    // so no common element exist
    public static int minRemove(int a[], int b[], int n,
                                                 int m)
    {
        // To store count of array element
        HashMap<Integer, Integer> countA = new HashMap<
                                          Integer, Integer>();
        HashMap<Integer, Integer> countB = new HashMap<
                                          Integer, Integer>();
      
        // Count elements of a
        for (int i = 0; i < n; i++){
           if (countA.containsKey(a[i]))
                countA.put(a[i], countA.get(a[i]) + 1);
            
           else countA.put(a[i], 1);
                
        }
         
        // Count elements of b
        for (int i = 0; i < m; i++){
             if (countB.containsKey(b[i]))
                    countB.put(b[i], countB.get(b[i]) + 1);
                
               else countB.put(b[i], 1);
        }
         
        // Traverse through all common element, and
        // pick minimum occurrence from two arrays
        int res = 0;
         
        Set<Integer> s = countA.keySet();
         
        for (int x : s)
            if(countB.containsKey(x))
                res += Math.min(countB.get(x),
                               countA.get(x));
      
        // To return count of minimum elements
        return res;
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
 
            int a[] = { 1, 2, 3, 4 };
            int b[] = { 2, 3, 4, 5, 8 };
            int n = a.length;
            int m = b.length;
          
            System.out.println(minRemove(a, b, n, m));
             
    }
}
   
// This code is contributed by Arnav Kr. Mandal.


Python3




# Python3 program to find minimum
# element to remove so no common
# element exist in both array
 
# To find no elements to remove
# so no common element exist
def minRemove(a, b, n, m):
 
    # To store count of array element
    countA = dict()
    countB = dict()
 
    # Count elements of a
    for i in range(n):
        countA[a[i]] = countA.get(a[i], 0) + 1
 
    # Count elements of b
    for i in range(n):
        countB[b[i]] = countB.get(b[i], 0) + 1
 
    # Traverse through all common
    # element, and pick minimum
    # occurrence from two arrays
    res = 0
    for x in countA:
        if x in countB.keys():
            res += min(countA[x],countB[x])
 
    # To return count of
    # minimum elements
    return res
 
# Driver Code
a = [ 1, 2, 3, 4 ]
b = [2, 3, 4, 5, 8 ]
n = len(a)
m = len(b)
print(minRemove(a, b, n, m))
 
# This code is contributed
# by mohit kumar


C#





Javascript




<script>
 
// JavaScript Code to Remove
// minimum number of elements
// such that no common element
// exist in both array
     
    // To find no elements to remove
    // so no common element exist
    function minRemove(a,b,n,m)
    {
        // To store count of array element
        let countA = new Map();
        let countB = new Map();
        
        // Count elements of a
        for (let i = 0; i < n; i++){
           if (countA.has(a[i]))
                countA.set(a[i],
                countA.get(a[i]) + 1);
              
           else
               countA.set(a[i], 1);
                  
        }
           
        // Count elements of b
        for (let i = 0; i < m; i++){
             if (countB.has(b[i]))
                    countB.set(b[i],
                    countB.get(b[i]) + 1);
                  
             else
                   countB.set(b[i], 1);
        }
         
           
        // Traverse through all
        // common element, and
        // pick minimum occurrence
        // from two arrays
        let res = 0;
           
           
        for (let x of countA.keys())
            if(countB.has(x))
                res += Math.min(countB.get(x),
                               countA.get(x));
        
        // To return count of minimum elements
        return res;
    }
     
    /* Driver program to test above function */
    let a=[1, 2, 3, 4 ];
    let b=[2, 3, 4, 5, 8];
    let n = a.length;
    let m = b.length;
    document.write(minRemove(a, b, n, m));
     
 
 
// This code is contributed by unknown2108
 
</script>


Output

3

Time Complexity: O(n+m)
Auxiliary Space: O(n+m)

 



Previous Article
Next Article

Similar Reads

Largest value of K such that both K and -K exist in Array in given index range [L, R]
Content has been removed on Author’s request.
1 min read
Count of Pairs in given Array having both even or both odd or sum as K
Given an array arr[] of distinct integers of size N and an integer K, The task is to find the total no of possible pairs in the array such that, either both are even or both are odd or the sum of the pair is K Note: No element is part of more than one pair. Examples: Input: N = 6, K = 7, arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Possible pair
7 min read
Divide array into two arrays with their sum as both odd or both even
Given an array arr[] consisting of N integers, the task is to check if it is possible to divide the entire array into two arrays such that the sum of elements in new arrays is either both odd or both even. Also, each new array must have at least one element. If it is possible, print “Yes”. Otherwise, print “No”. Examples: Input: arr[] = {3, 1, 1, 1
6 min read
Reduce Binary Array by replacing both 0s or both 1s pair with 0 and 10 or 01 pair with 1
Given a binary array arr[] of size N, the task is to find the last number remaining in the array after performing a set of operations. In each operation, select any two numbers and perform the following: If both numbers are the same, remove them from the array and insert a 0.If both numbers are different, remove both of them and insert a 1.Example:
9 min read
Minimum operations to choose Array elements with sum as K by choosing element from front, or rear or both
Given an array arr[] of positive integers of size N, and an integer K. The task is to minimize the number of operations required choose array elements that sum up to K. In one operation, an element can be removed either from the front, or from the rear, or from both front and rear, and added to the sum. If the desired sum can't be achieved, return
14 min read
Minimize operations to make both arrays equal by decrementing a value from either or both
Given two arrays A[] and B[] having N integers, the task is to find the minimum operations required to make all the elements of both the array equal where at each operation, the following can be done: Decrement the value of A[i] by 1 where i lies in the range [0, N).Decrement the value of B[i] by 1 where i lies in the range [0, N).Decrement the val
8 min read
Remove minimum elements from array such that no three consecutive element are either increasing or decreasing
Given an array of n distinct positive integers. The task is to find the minimum number of elements to be removed such that no three consecutive elements in the array are either increasing or decreasing. That is, after removal either ai - 1 &gt; ai &lt; ai + 1 or ai - 1 &lt; ai &gt; ai + 1. Examples : Input : arr[] = {5, 2, 3, 6, 1} Output : 1 Given
8 min read
Minimum count of array elements that must be changed such that difference between maximum and minimum array element is N - 1
Given an array arr[] consisting of N integers, the task is to find the minimum number of array elements that must be changed to any arbitrary integers such that the difference between maximum and minimum array element is (N - 1) and all array elements must be distinct. Examples: Input: arr[] = {1, 2, 3, 5, 6}Output: 1Explanation:Change 6-&gt;4, the
7 min read
Count pairs in an array such that both elements has equal set bits
Given an array arr [] of size N with unique elements, the task is to count the total number of pairs of elements that have equal set bits count. Examples: Input: arr[] = {2, 5, 8, 1, 3} Output: 4 Set bits counts for {2, 5, 8, 1, 3} are {1, 2, 1, 1, 2} All pairs with same set bits count are {2, 8}, {2, 1}, {5, 3}, {8, 1} Input: arr[] = {1, 11, 7, 3}
6 min read
Generate an Array such that Average of triplet exist in given Array
Given an array A[] of length N and your task is to find an array B[] of size N+2, such that Average of (B[i], B[i+1], B[i+2]) equals to A[i] for each i (1 &lt;= i &lt;= N) . Note: First two elements B[] must be zero. Examples:Input: N = 1, A[] = {3} Output: B[] = {0, 0, 9} Explanation: Let us understand it for each value of i (1 &lt;= i &lt;= 1) Fo
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg