Intersection of Two Arrays II in Python

Finding the intersection of two arrays means identifying common elements between them, preserving duplicates based on their frequency in both arrays. For example, if A = [1, 4, 5, 3, 6] and B = [2, 3, 5, 7, 9], the intersection will be [3, 5].

Algorithm Steps

To solve this problem efficiently, we follow these steps:

  • Take two arrays A and B
  • If length of A is smaller than length of B, swap them for optimization
  • Calculate the frequency of elements in the larger array and store them in a dictionary
  • For each element e in the smaller array, if e is present in the dictionary with non-zero frequency:
    • Decrease frequency of e by 1
    • Add e to the result array
  • Return the result array

Implementation

Here's the complete solution using a frequency counting approach:

class Solution:
    def intersect(self, nums1, nums2):
        """
        Find intersection of two arrays preserving duplicates
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        # Optimize by making nums1 the larger array
        if len(nums1) < len(nums2):
            nums1, nums2 = nums2, nums1
        
        # Count frequency of elements in nums1
        frequency = {}
        for num in nums1:
            if num not in frequency:
                frequency[num] = 1
            else:
                frequency[num] += 1
        
        # Find intersection by checking nums2 elements
        result = []
        for num in nums2:
            if num in frequency and frequency[num] > 0:
                frequency[num] -= 1
                result.append(num)
        
        return result

# Test the solution
solution = Solution()
print(solution.intersect([1, 4, 5, 3, 6], [2, 3, 5, 7, 9]))
[3, 5]

Using Collections Counter

Python's collections.Counter provides a cleaner approach for frequency counting:

from collections import Counter

def intersect_arrays(nums1, nums2):
    # Count frequencies in both arrays
    counter1 = Counter(nums1)
    counter2 = Counter(nums2)
    
    # Find intersection with minimum frequencies
    result = []
    for num in counter1:
        if num in counter2:
            # Add minimum count of each common element
            count = min(counter1[num], counter2[num])
            result.extend([num] * count)
    
    return result

# Test the function
print(intersect_arrays([1, 2, 2, 1], [2, 2]))
print(intersect_arrays([4, 9, 5], [9, 4, 9, 8, 4]))
[1, 2, 2]
[4, 9]

Time and Space Complexity

Approach Time Complexity Space Complexity
Frequency Dictionary O(m + n) O(min(m, n))
Counter Method O(m + n) O(m + n)

Where m and n are the lengths of the input arrays.

Conclusion

The frequency counting approach efficiently finds array intersections in linear time. The dictionary method optimizes space by using the smaller array for frequency counting, while Counter provides cleaner code for handling duplicate elements.

Updated on: 2026-03-25T07:18:41+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements