Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding intersection of arrays that contain repetitive entries in JavaScript
Finding the intersection of arrays with repetitive entries means identifying common elements between two arrays while preserving duplicate occurrences. This is different from a simple set intersection, as we need to consider the frequency of each element.
The function should build a third array based on the two input arrays that contains all the elements that are common to both arrays. If there are multiple instances of the same element present in both arrays, we need to include all such instances up to the minimum count found in either array.
Problem Example
If the input arrays are:
const arr1 = [1, 2, 2, 4, 4, 5, 6]; const arr2 = [3, 2, 4, 2, 4, 9];
Then the output array should be:
[2, 2, 4, 4]
This happens because:
- Element
2appears 2 times in arr1 and 2 times in arr2, so we include 2 instances - Element
4appears 2 times in arr1 and 2 times in arr2, so we include 2 instances - Other elements don't have common occurrences in both arrays
Using Map to Track Frequencies
const arr1 = [1, 2, 2, 4, 4, 5, 6];
const arr2 = [3, 2, 4, 2, 4, 9];
const findIntersection = (arr1 = [], arr2 = []) => {
const map = new Map();
// Count frequencies in second array
for (const el of arr2) {
const count = map.get(el) || 0;
map.set(el, count + 1);
}
// Filter first array based on available counts
return arr1.filter(el => {
let count = map.get(el);
if (count) {
map.set(el, --count);
return true;
}
return false;
});
};
console.log(findIntersection(arr1, arr2));
[2, 2, 4, 4]
How It Works
The algorithm works in two phases:
- Frequency Counting: Create a Map to store the frequency of each element in the second array
- Filtering: Iterate through the first array and include elements that have remaining count in the Map, decrementing the count each time
Alternative Approach Using Object
const findIntersectionWithObject = (arr1 = [], arr2 = []) => {
const frequency = {};
// Count frequencies in second array
for (const el of arr2) {
frequency[el] = (frequency[el] || 0) + 1;
}
const result = [];
for (const el of arr1) {
if (frequency[el] > 0) {
result.push(el);
frequency[el]--;
}
}
return result;
};
const arr1 = [1, 2, 2, 4, 4, 5, 6];
const arr2 = [3, 2, 4, 2, 4, 9];
console.log(findIntersectionWithObject(arr1, arr2));
[2, 2, 4, 4]
Comparison
| Approach | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Map-based filtering | O(n + m) | O(m) | Good |
| Object-based approach | O(n + m) | O(m) | Better |
Conclusion
Both approaches efficiently find array intersections with duplicate handling using frequency counting. The Map approach is more functional with filter(), while the Object approach offers clearer logic for beginners.
