Count Number of Nice Subarrays
MediumSliding Windowprefix sum
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given an integer array nums and an integer k, call a contiguous, non-empty subarray *nice* if it contains exactly k odd numbers.
Return the number of nice subarrays. Subarrays at different positions are counted separately even if their values are equal.
Aim for O(n) time.
Examples
Input: nums = [2,1,4,3,6], k = 2
Output: 4
A nice subarray must include both odd values 1 and 3; it can start at index 0 or 1 and end at index 3 or 4.
Input: nums = [2,4,6], k = 1
Output: 0
There are no odd numbers at all.
Constraints
- 1 <= nums.length <= 5 * 10^4
- 1 <= nums[i] <= 10^5
- 1 <= k <= nums.length
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.