Counting Subarrays with Exactly k Odd Numbers

Many subarray problems follow the same hidden pattern — once you recognize it, they become much easier. 🚀 Day 102/365 — DSA Challenge Solved: Count Number of Nice Subarrays Problem idea: We need to count the number of subarrays that contain exactly k odd numbers. Efficient approach: Use the same trick as previous problem: subarrays with exactly k odds = subarrays with ≤ k odds − subarrays with ≤ (k − 1) odds Steps: 1. Use a sliding window to count subarrays with at most k odd numbers 2. Expand window by moving right pointer 3. If odd count exceeds k, shrink window from left 4. Add valid subarrays ending at each index 5. Subtract results to get exact count This pattern works beautifully for binary-like conditions. ⏱ Time: O(n) 📦 Space: O(1) Day 102/365 complete. 💻 263 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #LeetCode #LearningInPublic

  • text

Great explanation, Anas! 🙌 Really like how you used the atMost approach here. Do you think this pattern can be extended to other conditions beyond odd numbers?

Like
Reply

To view or add a comment, sign in

Explore content categories