Count Number of Nice Subarrays
Problem Statement
You are given an array of positive integers nums and a number k.
A contiguous subarray is called nice if it contains exactly k odd numbers. Count the nice subarrays.
An integer array nums and an integer k.
The number of contiguous subarrays that contain exactly k odd numbers.
Only [1,1,2,1] (indices 0..3) and [1,2,1,1] (indices 1..4) contain exactly 3 odd numbers.
There are no odd numbers at all, so no subarray has exactly 1.
A nice subarray must contain both 1s. It can start at any of the 4 positions up to the first 1, and end at any of the 4 positions from the second 1 onward: 4 × 4 = 16.
- • 1 ≤ nums.length ≤ 5 · 10^4
- • 1 ≤ nums[i] ≤ 10^5
- • 1 ≤ k ≤ nums.length
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Fix each start, grow the end, count when the odd count hits k
Count earlier prefixes with (odds so far − k) odd numbers
Treat odd as 1 and even as 0, then use two at-most windows
For every start, move the end to the right and keep a running count of odd numbers. Count one each time it equals k. The odd count only goes up, so stop once it passes k.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.