AlgoInsight

DSA problem

Count Number of Nice Subarrays

MediumSliding Window - Dynamic SizePattern: Variable-Size Sliding Windowtop600AmazonGoogleMicrosoftFacebookTikTok

Given an array of integers nums and an integer k, a subarray is called nice if it contains exactly k odd numbers. Return the number of nice subarrays. A subarray is a contiguous, non-empty sequence of elements within the array.

Counting subarrays with an exact property is harder than finding the longest or shortest one, because a plain expand-and-shrink window measures lengths rather than counts. The standard technique converts the exact constraint into the difference of two at-most constraints.

The key identity is that the number of subarrays with exactly k odd numbers equals the number with at most k odd numbers minus the number with at most k - 1 odd numbers. Each of those at-most quantities is easy to compute with a single sliding window, because the count of odd numbers in a window grows monotonically as the window extends.

The intuition for the sliding window is the helper function for at most m odds. Expand the right pointer and track how many odd numbers the window holds; whenever that count exceeds m, shrink from the left. After each expansion, every subarray ending at the right pointer and starting anywhere inside the current window is valid, so we add the window width to a running total. Subtracting the two helper results gives the exact answer in linear time.

Examples

Example 1
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The subarrays with exactly 3 odd numbers are [1,1,2,1] and [1,2,1,1], so the count is 2.
Example 2
Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There are no odd numbers anywhere in the array, so no subarray can contain exactly one odd number and the answer is 0.
Example 3
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16
Explanation: Every nice subarray must span both odd numbers; counting the choices of left and right padding around them yields 16 subarrays.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

sliding-windowarraytwo-pointershash-tablemath

Browse all DSA problems