Count Number of Nice Subarrays

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an array of integers nums and an integer k, return the number of nice subarrays.

A nice subarray is a contiguous subarray with exactly k odd numbers.

Examples

Example 1:

Input: nums = [1,1,2,1,1], k = 3

Output: 2

Explanation: The only nice subarrays with exactly 3 odd numbers are [1,1,2,1] and [1,2,1,1].

Example 2:

Input: nums = [2,4,6], k = 1

Output: 0

Explanation: There are no odd numbers in the array, so no nice subarrays exist.

Example 3:

Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2

Output: 16

Explanation: The subarrays with exactly 2 odd numbers are counted using the sliding window atMost technique.

Constraints

  • 1 <= nums.length <= 5 * 10^4
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= nums.length
Source: Sliding Window pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle