Tensorum
YouTubeশেখা শুরু করুন
LeetCode 350 · Hashing / Anagram

Intersection of Two Arrays II

LeetCode 350 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Count the smaller array; consume counts while scanning the other.

সহজArrayHash TableTwo PointersBinary SearchSorting
LeetCode-এ খুলুন ↗

আমি Intersection of Two Arrays II (LeetCode 350) এভাবে সমাধান করেছি — Hashing / Anagram প্যাটার্নের একটি সহজ প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।

নিচের বিবরণ ইংরেজিতে।

Intuition

Count how many times each value appears in the smaller array, then walk the other array and take a value only while its count is still positive — that keeps the multiplicity right.

Approach

  1. 1

    Swap so nums1 is the smaller array (keeps the map small).

  2. 2

    Build a frequency map of nums1.

  3. 3

    For each value in nums2 with a positive count, append it and decrement.

আমি কীভাবে সমাধান করেছি

Hash map countsPythonO(n+m) time · O(min) space
class Solution:
    def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:
        n = len(nums1)
        m = len(nums2)
        res = []
        if n>m:
            return self.intersect(nums2,nums1)
        freq_map = defaultdict(int)
        for num in nums1:
            freq_map[num]+=1
        for num in nums2:
            if freq_map[num]>=1:
                freq_map[num]-=1
                res.append(num)
        return res
স্টেপ-থ্রু লোড হচ্ছে…

Intersection of Two Arrays II — সাধারণ প্রশ্ন

Intersection of Two Arrays II-এর পেছনে intuition কী?

Count how many times each value appears in the smaller array, then walk the other array and take a value only while its count is still positive — that keeps the multiplicity right.

Intersection of Two Arrays II (LeetCode 350) কীভাবে সমাধান করবেন?

1. Swap so nums1 is the smaller array (keeps the map small). 2. Build a frequency map of nums1. 3. For each value in nums2 with a positive count, append it and decrement.

Intersection of Two Arrays II-এর time আর space complexity কত?

Time: O(n + m)। Space: O(min(n, m))। (Accepted approach: Hash map counts।)

Intersection of Two Arrays II-এ সাধারণ ভুলগুলো কী?

Decrement the count so a value isn't used more times than it appears in both.