Subarrays with K Different Integers
LeetCode 992 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
exactly(k) = atMost(k) − atMost(k − 1) with a count map.
ನಾನು Subarrays with K Different Integers (LeetCode 992) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Counting Subarrays (Exactly K = AtMost K − AtMost K−1) ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
'Exactly k distinct' is hard to slide directly, but 'at most k distinct' is easy: keep a count map, shrink while it has more than k keys, and every right edge adds r − l + 1 windows. Then exactly(k) = atMost(k) − atMost(k − 1).
Approach
- 1
Add nums[r] to the map.
- 2
While more than k distinct values, remove nums[l] (delete at zero) and advance.
- 3
Add r − l + 1.
- 4
Return atMost(k) − atMost(k − 1).
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
atMost(k) − atMost(k−1)PythonO(n) time · O(k) space
class Solution:
def subarraysWithKDistinct(self, nums, k):
def getCountOfSubArrays(nums, k):
mpp = {}
l = 0
r = 0
count = 0
while r < len(nums):
mpp[nums[r]] = mpp.get(nums[r], 0) + 1
while len(mpp) > k:
mpp[nums[l]] -= 1
if mpp[nums[l]] == 0:
del mpp[nums[l]]
l += 1
count += r - l + 1
r += 1
return count
return getCountOfSubArrays(nums, k) - getCountOfSubArrays(nums, k - 1)Subarrays with K Different Integers — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Subarrays with K Different Integers ಹಿಂದಿನ intuition ಏನು?
'Exactly k distinct' is hard to slide directly, but 'at most k distinct' is easy: keep a count map, shrink while it has more than k keys, and every right edge adds r − l + 1 windows. Then exactly(k) = atMost(k) − atMost(k − 1).
Subarrays with K Different Integers (LeetCode 992) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Add nums[r] to the map. 2. While more than k distinct values, remove nums[l] (delete at zero) and advance. 3. Add r − l + 1. 4. Return atMost(k) − atMost(k − 1).
Subarrays with K Different Integers ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(k). (Accepted approach: atMost(k) − atMost(k−1).)