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.