Programming & Development / April 10, 2025

LeetCode 350: Intersection of Two Arrays II – Count Duplicates Efficiently

LeetCode 350 intersection of two arrays with duplicates Python Counter frequency count array problem hash map collections module two-pointer array intersection

🧩 Problem Statement

Given two integer arrays nums1 and nums2, return an array of their intersection, where each element in the result should 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

πŸ’‘ Intuition

Unlike LeetCode 349 (where elements are unique in the result), here, the number of times an element appears in the result depends on the minimum count it appears in both arrays.

βœ… Solution 1: Hash Map with collections.Counter

Python’s Counter makes it easy to track frequencies and find the intersection.

🐍 Python Code

python

from collections import Counter

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

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

        return result

πŸ” Step-by-Step Example

Input:

python

nums1 = [1, 2, 2, 1]
nums2 = [2, 2]

Step-by-step:

  • Create a counter for nums1: {1: 2, 2: 2}
  • Traverse nums2:
  • 2 is in the counter β†’ append 2, decrement counter β†’ now {1: 2, 2: 1}
  • 2 again β†’ append 2, decrement counter β†’ now {1: 2, 2: 0}
  • Result: [2, 2]

⏱️ Time & Space Complexity

MetricComplexityTimeO(n + m)SpaceO(min(n, m))

βœ… Solution 2: Two-Pointer After Sorting

This works well if you are allowed to sort the input.

🐍 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

  • Comparing event logs with repeated entries
  • Identifying shared transactions in two datasets
  • Detecting common items with frequency caps

βœ… Conclusion

LeetCode 350: Intersection of Two Arrays II is a practical problem that helps you practice:

  • Counting elements with dictionaries or Counter
  • Handling duplicates correctly
  • Optimizing with sorting and two pointers

Choose the method that best fits the problem constraints β€” Counter for simplicity, or sorting for optimized 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