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.