Code Logo

Array Intersection

Published at24 Jul 2026
PHP Data Structures Medium 0 views
Like0

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

Example 1
Input
[1,2,2,1],[2,2]
Output
[2,2]
Example 2
Input
[1,2,3],[4,5,6]
Output
[]
Example 3
Input
[],[]
Output
[]
Example 4
Input
[4,9,5],[9,4,9,8,4]
Output
[4,9]
Example 5
Input
[1],[1]
Output
[1]

Algorithm Flow

Recommendation Algorithm Flow for Array Intersection
Recommendation Algorithm Flow for Array Intersection

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 - Approach 1
<?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;
}