Skip to content
Veltoryx Technologies
ProProblem 33● MediumLeetCode #1248 ↗5 min readUpdated 30 October 2026

Count Number of Nice Subarrays

Count subarrays containing exactly k odd numbers by computing the difference of two monotonic sliding windows (atMost(k) - atMost(k - 1)).

01The problem

Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.

Return the number of nice sub-arrays.

InputOutputWhy
nums = [1, 1, 2, 1, 1], k = 32The two subarrays are [1, 1, 2, 1] and [1, 2, 1, 1]
nums = [2, 4, 6], k = 10There are no odd numbers in the array
nums = [2, 2, 2, 1, 2, 2, 1, 2, 2, 2], k = 2164 starting positions × 4 ending positions

Constraints: 1 to 50,000 numbers, 1 ≤ nums[i] ≤ 100,000, 1 ≤ k ≤ nums.length.

Loading the rest of the lesson…