1248 Count Number of Nice Subarrays in JavaScript

Day 20 of 30-day Coding Sprint Today I tackled 1248. Count Number of Nice Subarrays, which is a brilliant variation of the "Subarray Sum Equals K" problem, translated into parity (odd/even). 1248. Count Number of Nice Subarrays - The Problem: Find the total number of contiguous subarrays that contain exactly k odd numbers. - The Challenge: Unlike fixed-size windows, a "nice" subarray can have any number of even numbers surrounding the k odd ones. If you only count the minimal window, you miss all the valid subarrays formed by trailing/leading even numbers. - The Strategy: Three-Pointer / Temp Counter Logic Use r to expand and l to shrink the window when oddCount === k. The tempCount Trick: When we have exactly k odd numbers, we shrink from the left. Every even number we "skip" from the left still forms a valid "nice" subarray with the current right boundary. By tracking tempCount, we efficiently add up all those variations without re-scanning. - Result: O(N) time complexity and O(1) space—significantly better than the O(N) space required by a Prefix Sum + Hash Map approach. Note: This problem highlights the difference between finding the longest window and counting all windows. The tempCount reset logic (resetting when a new odd number enters from the right) is the key to handling the combinations of even numbers between odd peaks. #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #Algorithms #Consistency

  • text

To view or add a comment, sign in

Explore content categories