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

मैंने 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.