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.