Array Intersection
Write a PHP function that finds common elements between two arrays, handling duplicates correctly. Return each common element as many times as it appears in both arrays.
Build a frequency map from the first array using an associative array to count occurrences. Then iterate through the second array: for each element, if its count in the map is positive, add it to the result array and decrement the count.
This hash map approach handles duplicates correctly and runs in O(n + m) time, much better than the O(n*m) nested loop approach. The frequency map stores integer counts, not booleans, enabling accurate tracking of duplicate elements.
Edge cases include empty arrays (return []), arrays with no common elements (return []), and arrays where one value appears more times in one array than in the other.
Time complexity is O(n + m). Space complexity is O(min(n, m)).
The hash map approach for array intersection efficiently finds common elements by using associative arrays as lookup tables. This is much faster than nested loops for large arrays, reducing time complexity from O(n*m) to O(n+m).
The frequency map approach correctly handles duplicate elements by tracking counts, unlike a simple boolean set approach which would miss duplicates in the result.Example Input & Output
Algorithm Flow

Solution Approach
Write a PHP function that finds common elements between two arrays, handling duplicates correctly. Return each common element as many times as it appears in both arrays.
Build a frequency map from the first array using an associative array to count occurrences. Then iterate through the second array: for each element, if its count in the map is positive, add it to the result array and decrement the count.
This hash map approach handles duplicates correctly and runs in O(n + m) time, much better than the O(n*m) nested loop approach. The frequency map stores integer counts, not booleans, enabling accurate tracking of duplicate elements.
Edge cases include empty arrays (return []), arrays with no common elements (return []), and arrays where one value appears more times in one array than in the other.
Time complexity is O(n + m). Space complexity is O(min(n, m)).
Best Answers
<?php
function intersect($a, $b) {
$c=[];foreach($a as $v){$c[$v]=($c[$v]??0)+1;}$r=[];foreach($b as $v){if(($c[$v]??0)>0){$r[]=$v;$c[$v]--;}}return $r;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
