Problem 357362 · medium · Level 03 Linear Management & Searching

Runs with Exactly k Odd Numbers

sliding window · variable-size window · counting subarrays

Given a list of positive integers nums and an integer k, return the number of contiguous subarrays that contain exactly k odd numbers.

Examples

Input:  nums = [2, 1, 1, 4, 1], k = 2
Output: 5
Explanation: [2,1,1], [1,1], [2,1,1,4], [1,1,4] and [1,4,1].

Input:  nums = [6, 10, 4, 8], k = 1
Output: 0

Input:  nums = [6, 3, 4, 4, 5, 2, 8], k = 2
Output: 6
Explanation: a subarray must hold both 3 and 5: it starts at index 0 or 1 and ends at index 4, 5 or 6.

Constraints

  • 1 <= len(nums) <= 10**5, 1 <= nums[i] <= 10**5, 1 <= k <= len(nums)
  • Target complexity: O(n) time; checking every subarray is too slow for the largest tests.

Goals

  • Turn an 'exactly k' count into a difference of two 'at most' counts
  • Count subarrays with at most k of something in one sliding pass
Starting Python…