oneby7

Sliding Window Counting windows

183. Count Number of Nice Subarrays

Medium

You are given an array of integers nums and an integer k. A subarray is nice when exactly k of its elements are odd numbers. Return the number of nice subarrays.

A subarray is a contiguous sequence of elements from nums, with at least one element. Two subarrays are different if they start or end at different positions.

Example 1

Input: nums = [4, 7, 2, 9, 6, 5], k = 2

Output: 6

Explanation: Six subarrays hold exactly two odd numbers. Four hold 7 and 9: [4,7,2,9], [7,2,9], [4,7,2,9,6] and [7,2,9,6]. Two hold 9 and 5: [2,9,6,5] and [9,6,5].

Example 2

Input: nums = [-3, 0, 8, -5], k = 1

Output: 6

Explanation: -3 and -5 are odd, and 0 and 8 are even. Three subarrays hold -3 without -5, and three hold -5 without -3.

Example 3

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

Output: 4

Explanation: With k = 0, a nice subarray holds no odd number. The four are [10], [4], [10,4] and [8].

Check your understanding

Work out the answer for this input before you write any code.

nums = [-1, 2, -3], k = 1

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ nums.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.