Open In App

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

Last Updated : 24 Feb, 2025
Comments
Improve
Suggest changes
8 Likes
Like
Report

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.

Using Two Maps - O(n+m) Time and O(n+m) Space

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.

Below is the implementation of the above approach:

C++
Java Python C# JavaScript

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 for both the arrays

Using Single Map - O(n+m) Time and O(n) Space

The idea is to count occurrences of elements from arr1 using a single map. Then, while iterating through arr2, we check for common elements and decrement their count, adding to the result. One map is enough because we only need to track elements from arr1 and check for their existence in arr2, avoiding redundant storage.

Below is the implementation of the above approach:

C++
Java Python C# JavaScript

Output
3

Time Complexity: O(n+m), where m and n are the length of arr1 and arr2 respectively
Auxiliary Space: O(n), as we use a map to store elements of arr1.


Next Article
Practice Tags :

Similar Reads