Coding · stretch-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Count Number of Nice Subarrays
Problem
Given an integer array nums and an integer k, count the contiguous subarrays that contain exactly k odd numbers. Subarrays are identified by their position, so equal-looking subarrays at different positions count separately.
numshas between 1 and 50,000 positive integers.kis between 1 and the length ofnums.
Examples
nums = [3, 5, 8, 7, 9], k = 3→2.[3, 5, 8, 7]and[5, 8, 7, 9]each contain three odd numbers; the whole array contains four.nums = [4, 8, 10], k = 1→0. No odd numbers at all.nums = [6, 6, 3, 6, 6, 6, 5, 6, 6], k = 2→9. Both odd numbers must be included; there are 3 choices for the left boundary and 3 for the right.
Hints
- Replace each number by 1 if odd and 0 if even. What is the question now asking about that binary array?
- Counting subarrays with sum exactly
kcan be done with prefix sums and a hash map of how often each prefix value has occurred. - Alternatively, count windows with at most
kodds using a sliding window and subtract the count for at mostk - 1.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.