Skip to content
mlmentorship

Count Number of Nice Subarrays

Count subarrays that contain exactly `k` odd numbers.

Published · 13 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Count Number of Nice Subarrays

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. An integer list nums and a nonnegative integer odd_count. Output. Return the number of nonempty contiguous subarrays containing exactly odd_count odd values. Rules. Count ranges by their starting and ending positions, even when their values are identical. Values may be negative, zero, or repeated. Exactly zero odd values means an all-even range. Do not modify the input. An empty list contains zero qualifying ranges. Example. For nums = [1, 1, 2, 1, 1] and odd_count = 3, return 2. The zero-based inclusive ranges are [0..3] and [1..4]; both contain three odd values.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Count endings with at most 3 odds and at most 2 odds at every R, then subtract 14 - 12.

Problem trace

Subtract at-most counts to isolate starts with exactly three odd values

Worked example: fix the last endpoint of (2,2,2,1,1,1)Six starts contain at most three odds. Two contain at most two odds. Their difference leaves four starts containing exactly three.Keep start identities fixed at finalendpoint fiveInput: 2, 2, 2, 1, 1, 1At most three odds: all six starts012345At most two: only starts four andfive012345Exactly three: starts zero throughthree012345Six minus the same two starts leavesfour exact-three subarrays.
Read it this way: Six starts contain at most three odds. Two contain at most two odds. Their difference leaves four starts containing exactly three. Which starts remain after subtracting the at-most-two group from the at-most-three group?
Full interview answer 13 min read
Reading depth

Count contiguous input ranges containing exactly a requested number of odd integers.

Problem

Input. An integer list nums and a nonnegative integer odd_count.

Output. Return the number of nonempty contiguous subarrays containing exactly odd_count odd values.

Rules. Count ranges by their starting and ending positions, even when their values are identical. Values may be negative, zero, or repeated. Exactly zero odd values means an all-even range. Do not modify the input. An empty list contains zero qualifying ranges.

Example. For nums = [1, 1, 2, 1, 1] and odd_count = 3, return 2. The zero-based inclusive ranges are [0..3] and [1..4]; both contain three odd values.

Picture: Count Valid Starts at Each Ending

Problem trace

Separate full scan: add valid-start counts at every right endpoint

Input and goalCount subarrays that contain exactly `k` odd numbers.
Read the first odd at R = 0Both windows start at 0. Each has one valid ending at R, so totals become at_most(3) = 1 and at_most(2) = 1.
L<=3L<=2R1011221314
ranges<=3 [0..0]; <=2 [0..0]additions1 and 1totals1 and 1
L<
0
L<
0
R
0

Recognize it
Use it when subarrays must contain exactly k nonnegative events, while an at-most-k window can be repaired monotonically by moving its left boundary right.
Keep true
For each R, every start from L through R satisfies the relevant at-most limit, so that pass adds exactly R - L + 1 valid endings. The running total includes all right endpoints processed so far.
Reuse it
Convert exact monotone counts into at_most(k) - at_most(k - 1); at each right endpoint, the difference between the two valid-start ranges counts exactly-k subarrays ending there.
Both windows start at 0. Each has one valid ending at R, so totals become at_most(3) = 1 and at_most(2) = 1. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which start remains after subtracting the at-most-two starts at the final right endpoint?
Reference drawing

Problem trace

Subtract at-most counts to isolate starts with exactly three odd values

Worked example: fix the last endpoint of (2,2,2,1,1,1)Six starts contain at most three odds. Two contain at most two odds. Their difference leaves four starts containing exactly three.Keep start identities fixed at finalendpoint fiveInput: 2, 2, 2, 1, 1, 1At most three odds: all six starts012345At most two: only starts four andfive012345Exactly three: starts zero throughthree012345Six minus the same two starts leavesfour exact-three subarrays.
Execution trace
Input and goalCount subarrays that contain exactly `k` odd numbers.
Read the first odd at R = 0Both windows start at 0. Each has one valid ending at R, so totals become at_most(3) = 1 and at_most(2) = 1.
L<=3L<=2R1011221314
ranges<=3 [0..0]; <=2 [0..0]additions1 and 1totals1 and 1
L<
0
L<
0
R
0

Recognize it
Use it when subarrays must contain exactly k nonnegative events, while an at-most-k window can be repaired monotonically by moving its left boundary right.
Keep true
For each R, every start from L through R satisfies the relevant at-most limit, so that pass adds exactly R - L + 1 valid endings. The running total includes all right endpoints processed so far.
Reuse it
Convert exact monotone counts into at_most(k) - at_most(k - 1); at each right endpoint, the difference between the two valid-start ranges counts exactly-k subarrays ending there.
Both windows start at 0. Each has one valid ending at R, so totals become at_most(3) = 1 and at_most(2) = 1. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which start remains after subtracting the at-most-two starts at the final right endpoint?
Read it this way: Six starts contain at most three odds. Two contain at most two odds. Their difference leaves four starts containing exactly three. Which starts remain after subtracting the at-most-two group from the at-most-three group?

Only num % 2 is accumulated. Each contribution is 0 or 1, so extending a range cannot decrease its event count.

After repair, left is the earliest valid start for this right. Every start from left through right fits; add right - left + 1, not just one longest window. Earlier discarded starts stay invalid as right advances.

rightAt-most-3 additionAt-most-2 additionExactly-3 addition
0110
1220
2330
3431
4431
Total14122

The at-most-2 ranges are a subset of the at-most-3 ranges. Their difference leaves exactly three odds. Generally, exactly(k) = at_most(k) - at_most(k - 1).

Code

def number_of_nice_subarrays(nums: list[int], odd_count: int) -> int:
   def at_most(limit: int) -> int:
      if limit < 0:
         return 0

      left = 0
      total = 0
      for right, num in enumerate(nums):
         limit -= num % 2
         while limit < 0:
            limit += nums[left] % 2
            left += 1
         total += right - left + 1
      return total

   return at_most(odd_count) - at_most(odd_count - 1)

limit is the remaining budget: initial limit minus the current window’s odd count. Each boundary advances at most positions per pass: total time and auxiliary space under unit-cost arithmetic.

The negative-limit guard makes at_most(-1) zero. Thus [2, 4], count 0, returns three nonempty ranges without overrunning the array.

Change 1: Compute With Prefix Frequencies

New task. Use boundary counts instead of window repair.

Picture and change. Count earlier odd-prefix totals equal to prefix - odd_count.

Code.

def nice_by_prefix(nums, odd_count):
   counts = {0: 1}
   prefix = answer = 0
   for value in nums:
      prefix += value % 2
      answer += counts.get(prefix - odd_count, 0)
      counts[prefix] = counts.get(prefix, 0) + 1
   return answer

Check. The main input returns 2; [2, 4], count 0, returns 3.

Use when. A boundary-frequency derivation is easier to extend. This alternate uses state, not constant space.

Change 2: Count a Target Character

New task. Count ranges with exactly count occurrences of one target character; require count >= 0.

Picture and change. Replace parity with a 0/1 equality indicator.

Code.

def exact_character_ranges(text, target, count):
   counts = {0: 1}
   prefix = answer = 0
   for character in text:
      prefix += character == target
      answer += counts.get(prefix - count, 0)
      counts[prefix] = counts.get(prefix, 0) + 1
   return answer

Check. For text="aba", target "a", count 1 returns 4; count 0 returns 1 for "b".

Use when. The event changes but remains a nonnegative indicator.

Failure: Shrinking an Arbitrary Signed Sum

Signed values can decrease sums when appended; that invalidates this window-repair proof. Counting one start also misses valid ranges.

Transfer Check

Why are negative integers safe here?

Reasoned Answer

Parity contributes only 0 or 1. The original sign never becomes a negative event count.

Same Count, Different Proof and State

The trace’s R is code right; its two left pointers correspond to separate at_most calls. The visual synchronizes those calls for comparison; the implementation performs two linear passes.

For [-3, 2, -1], parity is [1, 0, 1]; exactly one odd occurs in four ranges. Empty input contributes no nonempty ranges. The public contract excludes negative requested counts.

Prefix frequency counts earlier boundaries, including the initial zero boundary. Querying before recording the current boundary excludes empty ranges, including when the requested count is zero. See signed prefix counting for the boundary-difference proof; it is not this window proof.