Programming & Development / April 10, 2025

LeetCode 350: Intersection of Two Arrays II – Handle Duplicates with Counters

LeetCode 350 Intersection of Arrays II Python Counter array intersection with duplicates frequency count collections module two-pointer technique hash map array problem

🧩 Problem Statement

Given two integer arrays nums1 and nums2, return an array of their intersection, where each element in the result must appear as many times as it shows in both arrays.
The result can be returned in any order.

🔢 Examples

python

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]  # or [9,4]

✅ Constraints

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

💡 Key Insight

Unlike LeetCode 349, duplicates matter here.

So we need to count the frequency of each element and find the minimum count of any overlapping number.

✅ Solution 1: Using collections.Counter

This is the most Pythonic and clean solution.

🐍 Python Code

python

from collections import Counter

class Solution:
    def intersect(self, nums1, nums2):
        counts1 = Counter(nums1)
        result = []

        for num in nums2:
            if counts1[num] > 0:
                result.append(num)
                counts1[num] -= 1

        return result

📋 Step-by-Step Example

Input:

python

nums1 = [1, 2, 2, 1]
nums2 = [2, 2]
  • Counter of nums1: {1:2, 2:2}
  • Loop through nums2:
  • 2 → in counts1 → append 2, decrease count → {1:2, 2:1}
  • 2 again → append 2, decrease count → {1:2, 2:0}
  • Result: [2, 2]

⏱️ Time & Space Complexity

MetricValueTime ComplexityO(n + m)Space ComplexityO(min(n, m))

✅ Solution 2: Sorting + Two Pointers

Works well when you can sort the arrays.

🐍 Python Code

python

class Solution:
    def intersect(self, nums1, nums2):
        nums1.sort()
        nums2.sort()
        i = j = 0
        result = []

        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                result.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1

        return result

🧠 Use Cases

  • Frequency matching in text analysis
  • Log comparisons with repeated events
  • Database join operations with value repetition

✅ Conclusion

LeetCode 350: Intersection of Two Arrays II teaches the importance of handling duplicate values properly.

  • collections.Counter gives you an easy and efficient solution.
  • Two-pointer method is great when sorting is allowed and you're optimizing for space.

Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex