The Wayback Machine - https://web.archive.org/web/20241127030444/https://www.geeksforgeeks.org/remove-minimum-number-elements-no-common-element-exist-array/
Open In App

Remove minimum elements such that no common elements exist in two arrays

Last Updated : 07 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two arrays arr1[] and arr2[] consisting of n and m elements respectively. The task is to find the minimum number of elements to remove from each array such that intersection of both arrays becomes empty and both arrays become mutually exclusive.

Examples: 

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

Input: arr[] = { 4, 2, 4, 4}, arr2[] = { 4, 3 }
Output: 1
Explanation: We need to remove 4 from arr2[]

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

The idea is to use Hashing We first count the frequency of each element in both arrays using two map data structures. After counting, iterates through all elements in the first map (countA). For each element that appears in both maps, adds the minimum frequency of that element in both arrays to a result variable (res). This sum represents the minimum number of removals required to remove all common elements between the two arrays.

C++
// CPP program to find minimum element to remove so no common element
// exist in both array

#include <bits/stdc++.h>
using namespace std;

// To find no elements to remove
// so no common element exist
int minRemove(vector<int>& arr1, vector<int>& arr2)
{
    // To store count of array elements
    unordered_map<int, int> countA, countB;

    // Count elements of arr1
    for (int i = 0; i < arr1.size(); i++)
        countA[arr1[i]]++;

    // Count elements of arr2
    for (int i = 0; i < arr2.size(); i++)
        countB[arr2[i]]++;

    // Traverse through all common elements, and
    // pick minimum occurrence from two arrays
    int res = 0;
    for (auto x : countA)
        if (countB.find(x.first) != countB.end())
            res += min(x.second, countB[x.first]);

    // To return count of minimum elements
    return res;
}

int main()
{
    vector<int> arr1 = { 1, 2, 3, 4 };
    vector<int> arr2 = { 2, 3, 4, 5, 8 };

    cout << minRemove(arr1, arr2);

    return 0;
}
Java
// Java Code to Remove minimum number of elements
// such that no common element exist in both array
import java.util.HashMap;

class GfG {

    static int minRemove(int[] arr1, int[] arr2) {
        HashMap<Integer, Integer> countA = new HashMap<>();
        HashMap<Integer, Integer> countB = new HashMap<>();
        int res = 0;

        // Count elements of arr1
        for (int num : arr1) {
            countA.put(num, countA.getOrDefault(num, 0) + 1);
        }

        // Count elements of arr2
        for (int num : arr2) {
            countB.put(num, countB.getOrDefault(num, 0) + 1);
        }

        // Traverse through all common elements, and pick minimum 
        // occurrence from two arrays
        for (int key : countA.keySet()) {
            if (countB.containsKey(key)) {
                res += Math.min(countA.get(key), countB.get(key));
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4};
        int[] arr2 = {2, 3, 4, 5, 8};

        System.out.println(minRemove(arr1, arr2));
    }
}
Python
# Python3 program to find minimum element to remove so no common 
# element exist in both array

from collections import Counter

def minRemove(arr1, arr2):
    countA = Counter(arr1)
    countB = Counter(arr2)
    res = 0

    # Traverse through all common elements, and pick minimum
    # occurrence from two arrays
    for key in countA:
        if key in countB:
            res += min(countA[key], countB[key])

    return res

arr1 = [1, 2, 3, 4]
arr2 = [2, 3, 4, 5, 8]

print(minRemove(arr1, arr2))
C#
// C# Code to Remove minimum number of elements
// such that no common element exist in both array

using System;
using System.Collections.Generic;

class GfG
{
    static int MinRemove(int[] arr1, int[] arr2)
    {
        Dictionary<int, int> countA = new Dictionary<int, int>();
        Dictionary<int, int> countB = new Dictionary<int, int>();
        int res = 0;

        // Count elements of arr1
        foreach (int num in arr1)
        {
            if (countA.ContainsKey(num))
                countA[num]++;
            else
                countA[num] = 1;
        }

        // Count elements of arr2
        foreach (int num in arr2)
        {
            if (countB.ContainsKey(num))
                countB[num]++;
            else
                countB[num] = 1;
        }

        // Traverse through all common elements, and pick minimum
        // occurrence from two arrays
        foreach (var key in countA.Keys)
        {
            if (countB.ContainsKey(key))
            {
                res += Math.Min(countA[key], countB[key]);
            }
        }

        return res;
    }

    static void Main(string[] args)
    {
        int[] arr1 = { 1, 2, 3, 4 };
        int[] arr2 = { 2, 3, 4, 5, 8 };

        Console.WriteLine(MinRemove(arr1, arr2));
    }
}
JavaScript
// Javascript program to find minimum element to remove
//  so no common element exist in both array

function minRemove(arr1, arr2) {
    let countA = {};
    let countB = {};
    let res = 0;

    // Count elements of arr1
    for (let num of arr1) {
        countA[num] = (countA[num] || 0) + 1;
    }

    // Count elements of arr2
    for (let num of arr2) {
        countB[num] = (countB[num] || 0) + 1;
    }

    // Traverse through all common elements, and pick minimum
    // occurrence from two arrays
    for (let key in countA) {
        if (countB.hasOwnProperty(key)) {
            res += Math.min(countA[key], countB[key]);
        }
    }

    return res;
}

const arr1 = [1, 2, 3, 4];
const arr2 = [2, 3, 4, 5, 8];

console.log(minRemove(arr1, arr2));

Output
3

Time Complexity: O(n+m), where m and n are the length of arr1 and arr2 respectively
Auxiliary Space: O(n+m), For storing the frequency in map



Previous Article
Next Article

Similar Reads

Minimum sum of two elements from two arrays such that indexes are not same
Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays. Examples: Input : a[] = {5, 4, 13, 2, 1} b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input : a[] = {5, 4, 13, 1} b[] = {3, 2, 6, 1}Output : 3
15+ min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Find sub-arrays from given two arrays such that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4} Output: Indices in array 1 : 0, 1
15+ min read
Check if X and Y elements can be selected from two arrays respectively such that the maximum in X is less than the minimum in Y
Given two arrays arr1[] and arr2[] consisting of N and M integers respectively, and two integers X and Y, the task is to check if it is possible to choose X elements from arr1[] and Y elements from arr2[] such that the largest among these X elements is less than the minimum element among these Y elements. If it is possible, then print "Yes". Otherw
15 min read
Count common elements in two arrays which are in Arithmetic Progression
Given two arrays arr1[] and arr2[] of size M and N respectively. Both arrays are in Arithmetic Progression and the first element of both arrays is the same. The task is to find the number of common elements in arr1[] and arr2[].Examples: Input: arr1[] = {2, 3, 4, 5, 6}, arr2[] = {2, 4, 6, 8, 10} Output: 3 Explanation: Common elements are {2, 4, 6}I
15+ min read
Longest Common Subsequence of two arrays out of which one array consists of distinct elements only
Given two arrays firstArr[], consisting of distinct elements only, and secondArr[], the task is to find the length of LCS between these 2 arrays. Examples: Input: firstArr[] = {3, 5, 1, 8}, secondArr[] = {3, 3, 5, 3, 8}Output: 3.Explanation: LCS between these two arrays is {3, 5, 8}. Input : firstArr[] = {1, 2, 1}, secondArr[] = {3}Output: 0 Naive
7 min read
Find Common Elements in Two Arrays in Python
Given two arrays arr1[] and arr2[], the task is to find all the common elements among them. Examples: Input: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {3, 4, 5, 6, 7}Output: 3 4 5Explanation: 3, 4 and 5 are common to both the arrays. Input: arr1: {2, 4, 0, 5, 8}, arr2: {0, 1, 2, 3, 4}Output: 0 2 4Explanation: 0, 2 and 4 are common to both the arrays. Find
8 min read
Count number of common elements between two arrays
Given two arrays a[] and b[], the task is to find the count of common elements in both the given arrays. Note that both the arrays contain distinct (individually) positive integers.Examples: Input: a[] = {1, 2, 3}, b[] = {2, 4, 3} Output: 2 2 and 3 are common to both the arrays.Input: a[] = {1, 4, 7, 2, 3}, b[] = {2, 11, 7, 4, 15, 20, 24} Output: 3
15 min read
Common Elements in Two Arrays
Given two arrays, the task is find common elements of the two arrays. The input arrays may contain duplicates and our job is to find all common elements We are allowed to return elements in any order. Input : a[] = {1, 2, 1, 3, 1}, b[] = {3, 1, 3, 4, 1}Output : {1, 3, 1}1 appears two times in both the input arrays. Input : a[] = {1, 1, 1}, b[] = {1
9 min read
Common Elements in Two Sorted Arrays
Given two sorted arrays a[] and b[]. The task is to return the common elements of both arrays. If an element appears more than once in both array, we need to pick minimum of its two frequencies Examples: Input: a[] = [1, 1, 2, 2, 2, 4], b[] = [2, 2, 4, 4]Output: [2, 2, 4]Explanation: 2 and 4 are only common elements and 2 appears two times in both
7 min read
Number of triangles formed by joining vertices of n-sided polygon with two common sides and no common sides
Given N-sided polygon we need to find the total number of triangles formed by joining the vertices of the given polygon with exactly two sides being common and no side being common.Examples: Input : N = 6 Output : 6 2 The image below is of a triangle forming inside a Hexagon by joining vertices as shown above. The triangle formed has two sides (AB
5 min read
Remove Minimum coins such that absolute difference between any two piles is less than K
Given an array, arr[] of size N and an integer K which means there are N piles of coins and the ith contains arr[i] coins. The task is to adjust the number of coins in each pile such that for any two piles if a be the number of coins in the first pile and b be the number of coins in the second pile then |a - b| <= K. One can remove coins from di
7 min read
Check if there exist two elements in an array whose sum is equal to the sum of rest of the array
We have an array of integers and we have to find two such elements in the array such that sum of these two elements is equal to the sum of rest of elements in array. Examples: Input : arr[] = {2, 11, 5, 1, 4, 7} Output : Elements are 4 and 11 Note that 4 + 11 = 2 + 5 + 1 + 7 Input : arr[] = {2, 4, 2, 1, 11, 15} Output : Elements do not exist A simp
15+ min read
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
Check if there exist a string Y such that (X+Y) and (Y+X) are palindromes
Given a string X of length N and an integer K, the task is to determine if there exists a string (say Y) of length K such that its concatenation on either side of X makes the resultant string palindrome i.e. X+Y and Y+X both are palindromes. Examples: Input: N = 6, K = 2, X = "abbaab"Output: YesExplanation: Let string Y = "ba". Then, X + Y = "abbaa
10 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 <= i <= 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 <= i <= 1) Fo
5 min read
Minimum common sum from K arrays after removing some part of their suffix
Given K (K > 2) arrays of different sizes in a 2D list arr[][] where elements in each array are non-negative. Find the minimum common sum of K arrays after removing part of the suffix(possibly none) from each array. Examples: Input: K = 3, arr = {{5, 2, 4}, {1, 4, 1, 1}, {2, 3}}Output: 5Explanation: 1st array: [5, 5+2, 5+2+4], = {5, 7, 11} remov
7 min read
Generate all possible sorted arrays from alternate elements of two given sorted arrays
Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B. Example: A = {10, 15, 25} B = {1, 5, 20, 30} The resulting arrays are: 10 20 10 20 25 30 10 30 15 20 1
12 min read
Length of longest common prime subsequence from two given arrays
Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays. Examples: Input: arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, arr2[] = {2, 5, 6, 3, 7, 9, 8} Output: 4 Explanation: The longest common prime subsequence present in both th
11 min read
Longest common subarray in the given two arrays
Given two arrays A[] and B[] of N and M integers respectively, the task is to find the maximum length of an equal subarray or the longest common subarray between the two given array. Examples: Input: A[] = {1, 2, 8, 2, 1}, B[] = {8, 2, 1, 4, 7} Output: 3 Explanation: The subarray that is common to both arrays are {8, 2, 1} and the length of the sub
15+ min read
Remove the common nodes in two Singly Linked Lists
Given two Linked Lists L1 and L2, the task is to generate a new linked list with no common elements from the given two linked lists. Example: Input: L1 = 10 -> 15 -> 5 -> 20, L2 = 8 -> 5 -> 20 -> 10 Output: 8 -> 15 Explanation: Since both the linked list has 5, 10 and 20 in common. Therefore these elements are removed and the r
10 min read
Python program to remove words that are common in two Strings
Given two strings S1 and S2, representing sentences, the task is to print both sentences after removing all words which are present in both sentences. Input: S1 = "sky is blue in color", S2 ="Raj likes sky blue color "Output: is in Raj likes Explanation: The common words are [ sky, blue, color ]. Removing these words from the two sentences modifies
7 min read
Minimum swaps of similar indexed elements required to make all elements of one of the two given arrays equal
Given two arrays A[] and B[] of size N, the task is to count the minimum number of swaps of similar indexed elements required to make one of the two given arrays equal. If it is not possible to make all elements of an array equal, then print -1. Examples: Input: A[] = {3, 4, 1, 3, 1, 3, 4}, B[] = {1, 3, 3, 1, 3, 4, 3}Output: 3Explanation: Swapping
12 min read
Minimum Index Sum for Common Elements of Two Lists
Ram and Shyam want to choose a website to learn programming and they both have a list of favorite websites represented by strings.You need to help them find out their common interest with the least index sum. If there is a choice tie between answers, print all of them with no order requirement. Assume there always exists an answer. Examples: Input
11 min read
Distribute given arrays into K sets such that total sum of maximum and minimum elements of all sets is maximum
Given two arrays, the first arr[] of size N and the second brr[] of size K. The task is to divide the first array arr[] into K sets such that the i-th set should contain brr[i] elements from the second array brr[], and the total sum of maximum and minimum elements of all sets is maximum. Examples: Input: n = 4, k = 2, arr[] = {10, 10, 11, 11 }, brr
8 min read
Remove minimum elements from the array such that 2*min becomes more than max
Given an array of size N. The task is to remove minimum elements from the array such that twice of minimum number is greater than the maximum number in the modified array. Print the minimum number of elements removed.Examples: Input: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 Remove 4 elements (4, 5, 100, 200) so that 2*min becomes more
6 min read
Remove minimum elements from either side such that 2*min becomes more than max
Given an unsorted array, trim the array such that twice of minimum is greater than maximum in the trimmed array. Elements should be removed either end of the array.Number of removals should be minimum. Examples: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 We need to remove 4 elements (4, 5, 100, 200) so that 2*min becomes more than max. a
15+ min read
Remove minimum elements from either side such that 2*min becomes more than max | Set 2
Given an unsorted array, trim the array such that twice of minimum is greater than the maximum in the trimmed array. Elements should be removed from either end of the array. The number of removals should be minimum. Examples: Input: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 We need to remove 4 elements (4, 5, 100, 200) so that 2*min bec
15+ 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 > ai < ai + 1 or ai - 1 < ai > ai + 1. Examples : Input : arr[] = {5, 2, 3, 6, 1} Output : 1 Given
8 min read
Choose two elements from the given array such that their sum is not present in any of the arrays
Given two arrays A[] and B[], the task is to choose two elements X and Y such that X belongs to A[] and Y belongs to B[] and (X + Y) must not be present in any of the array.Examples: Input: A[] = {3, 2, 2}, B[] = {1, 5, 7, 7, 9} Output: 3 9 3 + 9 = 12 and 12 is not present in any of the given arrays.Input: A[] = {1, 3, 5, 7}, B[] = {7, 5, 3, 1} Out
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg