Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Amazon
Count Number Of Nice Subarrays

Count the number of contiguous subarrays that contain exactly kk odd numbers.

Acceptance 100%
Also Available On
Other platform versions and source mappings for the same problem.

Nice Subarrays

gfg
Problem Statement

Given an integer array nums and an integer k, count how many contiguous subarrays contain exactly k odd numbers.

A subarray is a contiguous non-empty portion of the array. A subarray is considered nice if it contains exactly k elements whose values are odd.

Input Format

  • nums: an integer array
  • k: a positive integer

Return the number of contiguous subarrays with exactly k odd numbers.

Output Format

  • Return a single integer: the number of nice subarrays.

Constraints

  • The subarray must be contiguous.
  • Count subarrays with exactly k odd elements.
  • nums is non-empty in the original problem formulation.
  • A linear or near-linear solution is expected for interview use.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

2

Explanation

The nice subarrays 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, so no subarray can contain exactly 1 odd number.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.