Count Number of Nice Subarrays
LeetCode 1248 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Odd → 1, then exactly(k) = atMost(k) − atMost(k − 1).
ನಾನು Count Number of Nice Subarrays (LeetCode 1248) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Counting Subarrays (Exactly K = AtMost K − AtMost K−1) ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Replace each number by 1 if odd and 0 if even; now 'k odd numbers' means 'sum exactly k' — the same trick as binary subarrays: atMost(k) − atMost(k − 1).
Approach
- 1
Sliding window over nums[i] % 2.
- 2
Shrink while the odd count exceeds k.
- 3
Add r − l + 1 per right edge.
- 4
Subtract the atMost(k − 1) count.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
atMost(k) − atMost(k−1)PythonO(n) time · O(1) space
class Solution:
def getCountSubArray(self, nums, k):
if k < 0:
return 0
cnt = 0
total = 0
l = 0
for r in range(len(nums)):
total += nums[r] % 2
while total > k:
total = total - nums[l] % 2
l += 1
if total <= k:
cnt += r - l + 1
return cnt
def numberOfSubarrays(self, nums, k):
return self.getCountSubArray(nums, k) - self.getCountSubArray(nums, k - 1)Count Number of Nice Subarrays — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Count Number of Nice Subarrays ಹಿಂದಿನ intuition ಏನು?
Replace each number by 1 if odd and 0 if even; now 'k odd numbers' means 'sum exactly k' — the same trick as binary subarrays: atMost(k) − atMost(k − 1).
Count Number of Nice Subarrays (LeetCode 1248) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Sliding window over nums[i] % 2. 2. Shrink while the odd count exceeds k. 3. Add r − l + 1 per right edge. 4. Subtract the atMost(k − 1) count.
Count Number of Nice Subarrays ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(1). (Accepted approach: atMost(k) − atMost(k−1).)
Count Number of Nice Subarrays ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Same atMost trick — only the value mapping changes.