Count Number of Nice Subarrays solution explained
Count Number of Nice Subarrays asks how many contiguous subarrays contain exactly k odd numbers. Replace each value with 1 if it is odd and 0 if it is even; the question becomes how many subarrays sum to k, which a running count and a hash map of earlier counts answer in one O(n) pass. A sliding window also works: count subarrays with at most k odd values, subtract those with at most k - 1, and the difference is exactly k, in O(n) time and O(1) memory.
By Evin JohnPublished 7 min read
The problem, reworded
You get an array of integers and a number k. A subarray is a contiguous slice, defined by a start and end position. Call it nice if exactly k of its values are odd. Count the nice subarrays. Two slices with the same values at different positions count separately. Even values do not matter except that they stretch the slices around the odd ones.
| Values | k | Count |
|---|---|---|
[2, 3, 4, 5, 6] | 1 | 8 |
[2, 3, 4, 5, 6] | 2 | 4 |
[1, 1, 1] | 2 | 2 |
[7, 2, 2, 9, 3] | 2 | 4 |
[8, 0, 4] | 1 | 0 |
[8, 0, 4] | 0 | 6, every slice has zero odd values |
What the interviewer is looking for
The first move they hope to see is the reduction: odd becomes 1, even becomes 0, and "exactly k odd values" becomes "subarray sum equals k" on a 0/1 array. From there, either the prefix-sum hash map or the at-most window is a full answer. Strong candidates explain why a plain sliding window cannot count "exactly k" directly: when the window has exactly k odd values, extending it with even numbers keeps it nice, so there is no single correct moment to shrink.
Brute force
def nice_brute(nums, k):
count = 0
for i in range(len(nums)):
odd = 0
for j in range(i, len(nums)):
odd += nums[j] % 2
if odd == k:
count += 1
elif odd > k:
break
return countPython's % returns 0 or 1 for any integer, including negatives, so nums[j] % 2 is a safe odd test there. In JavaScript, -3 % 2 is -1, so use Math.abs(x % 2) or x & 1 for values that fit in 32 bits.
Linear answer one: prefix counts
Let odd be the number of odd values seen so far. A subarray ending at the current position with exactly k odd values corresponds to an earlier prefix whose odd count was odd - k. So keep a map from odd count to how many prefixes had it, starting with one empty prefix at count 0, and for each position add the number of earlier prefixes at odd - k. This is the same frame as the subarray-sum-equals-k problem, specialized to 0/1 values.
def nice_prefix(nums, k):
seen = {0: 1} # odd count of a prefix -> how many prefixes
odd = total = 0
for x in nums:
odd += x % 2
total += seen.get(odd - k, 0)
seen[odd] = seen.get(odd, 0) + 1
return totalfunction nicePrefix(nums, k) {
const seen = new Array(nums.length + 1).fill(0);
seen[0] = 1;
let odd = 0;
let total = 0;
for (const x of nums) {
odd += Math.abs(x % 2);
if (odd - k >= 0) total += seen[odd - k];
seen[odd] += 1;
}
return total;
}Linear answer two: at most k, minus at most k - 1
"At most k odd values" does work with a forward-only window: if a slice has at most k, so does any slice inside it. For each right edge, move the left edge forward until the window has at most k odd values; then every start from the left edge to the right edge gives a valid slice, which is right - left + 1 slices. Summing those counts all slices with at most k odd values. Do it again with k - 1 and subtract.
def nice_window(nums, k):
def at_most(limit):
if limit < 0:
return 0
left = odd = count = 0
for right, x in enumerate(nums):
odd += x % 2
while odd > limit:
odd -= nums[left] % 2
left += 1
count += right - left + 1
return count
return at_most(k) - at_most(k - 1)function niceWindow(nums, k) {
const atMost = (limit) => {
if (limit < 0) return 0;
let left = 0, odd = 0, count = 0;
for (let right = 0; right < nums.length; right++) {
odd += Math.abs(nums[right] % 2);
while (odd > limit) {
odd -= Math.abs(nums[left] % 2);
left++;
}
count += right - left + 1;
}
return count;
};
return atMost(k) - atMost(k - 1);
}A third view: gaps around the odd numbers
List the positions of the odd values, with sentinels at -1 and n. A nice slice uses some run of k consecutive odd positions. It may start anywhere after the previous odd value and up to the first odd value in the run, and end anywhere from the last odd value in the run up to just before the next one. Multiply the two gap sizes and add over every run. For [7, 2, 2, 9, 3] with k = 2, the run 7, 9 gives 1 × 1 and the run 9, 3 gives 3 × 1, total 4. This view does not handle k = 0 directly; count the stretches of even values separately for that case.
def nice_gaps(nums, k):
pos = [-1] + [i for i, x in enumerate(nums) if x % 2] + [len(nums)]
total = 0
for a in range(1, len(pos) - k):
b = a + k - 1 # run pos[a] .. pos[b]
total += (pos[a] - pos[a - 1]) * (pos[b + 1] - pos[b])
return totalComplexity side by side
| Approach | Time | Extra space |
|---|---|---|
| Brute force with early stop | O(n²) | O(1) |
| Prefix counts in a map | O(n) | O(n) |
| atMost(k) - atMost(k - 1) | O(n), two passes | O(1) |
| Gaps between odd positions | O(n) | O(n) for the positions |
Inputs to try
- k larger than the number of odd values: the answer is 0.
- k = 0, which counts slices made only of even values.
- All odd values, such as
[1, 1, 1]. - Negative odd values, which catch a JavaScript
% 2test that returns -1. - Long runs of even values at both ends, which multiply the count.
- An empty array: 0.
Typical mistakes
- Trying to count exactly k with one window and shrinking at the wrong moment.
- Forgetting the empty prefix (
seen[0] = 1), which misses slices that start at index 0. - Updating the map before reading it, which counts a slice of length zero when k is 0.
- Calling
at_most(-1)without the guard, which loops forever or goes out of bounds. - Testing odd values with
x % 2 === 1in JavaScript, which is false for negative odd numbers.
How to explain it
Fictional example
- Candidate
- Only parity matters, so I'll think of odd as 1 and even as 0. Now I'm counting subarrays with sum k on a 0/1 array.
- Candidate
- For each end, the slices that work are the ones whose start prefix had k fewer odd numbers. A map from prefix odd count to frequency gives me that in constant time, so one pass.
- Candidate
- If memory matters, at most k is easy with a window, because removing values from the left never adds odd numbers. Exactly k is at most k minus at most k minus one.
Related problems
Subarrays with K Different Integers uses the same subtraction, but there the prefix-sum shortcut does not work, because distinct counts do not add up across slices. Substring with Concatenation of All Words is a window that slides in word-sized steps. For a hash map of earlier values in its simplest form, see Two Sum.
Natively in your practice sessions
When you rehearse on a Mac or Windows computer, Natively can pick up a counting problem like this from a screenshot and give an approach and code, which is a handy second opinion when your prefix map is off by one. It also transcribes the mock interview, so you can review whether you stated the 0/1 reduction early, which is the line interviewers wait for. Learn about an AI interview assistant for practice.
Questions people ask
How do you count subarrays with exactly k odd numbers?
Treat odd as 1 and even as 0, then count subarrays summing to k: keep a running odd count and a map of how many earlier prefixes had each count, adding the count at odd - k.
Why does atMost(k) - atMost(k - 1) work?
Every subarray with exactly k odd values is counted by atMost(k) but not by atMost(k - 1). At most k is monotone, so a forward-only window counts it.
Why can't one sliding window count exactly k directly?
A window with exactly k odd values stays valid when you add even numbers, so there is no single right moment to shrink.
What is the space complexity?
O(n) for the prefix map, or O(1) for the two-window subtraction.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
