Skip to content

350. Intersection of Two Arrays II #123

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

To solve this problem, we can follow these steps:

Let's implement this solution in PHP: 350. Intersection of Two Arrays II

<?php
/**
 * @param Integer[] $nums1
 * @param Integer[] $nums2
 * @return Integer[]
 */
    function intersect($nums1, $nums2) {
        // Count occurrences of each element in both arrays
        $counts1 = array_count_values($nums1);
        $counts2 = array_count_values($nums2);

        $intersection = [];

        // Iterate through the first count array
        foreach ($counts1 as $num => $count) {
            // Check if the element exists in the second array
            if (isset($counts2[$num])) {
                // Find the minimum occurrence
                

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@topugit
Comment options

topugit Aug 27, 2024
Collaborator

@mah-shamim
Comment options

mah-shamim Aug 27, 2024
Maintainer Author

Answer selected by topugit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants