Intersection of Two Arrays II
LeetCode 350 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Count the smaller array; consume counts while scanning the other.
मी 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
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.
मी कसा सोडवला
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 resIntersection 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.