![]() |
VOOZH | about |
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.
Table of Content
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:
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
The idea is to count occurrences of elements from
arr1using a single map. Then, while iterating througharr2, we check for common elements and decrement their count, adding to the result. One map is enough because we only need to track elements fromarr1and check for their existence inarr2, avoiding redundant storage.
Below is the implementation of the above approach:
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.