Count Subarrays Containing Exactly k Odd Values

Quick Overview

Count Subarrays Containing Exactly k Odd Values. Return the number of nonempty contiguous subarrays of nums containing exactly k odd elements.

Count Subarrays Containing Exactly k Odd Values

Company: InMobi

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Return the number of nonempty contiguous subarrays of nums containing exactly k odd elements. Even elements may appear anywhere within those intervals. ```cpp class Solution { public: int numberOfSubarrays(vector<int>& nums, int k); }; ``` ### Examples **Example 1:** ```text Input: nums = [2,1,2,1,2], k = 2 Output: 4 Explanation: A valid interval starts at0 or1 and ends at3 or4, giving2*2 choices. ``` **Example 2:** ```text Input: nums = [1,2,1], k = 1 Output: 4 Explanation: The intervals are[1] at either end,[1,2],and[2,1]. ``` ### Constraints - There are 1 to 50000 elements. - Each nums value is an integer in `[1,100000]`. - `1 <= k <= nums.length`. ### Contract considerations The source has positive input values, but only their odd/even status matters. ```hint Read the boundary condition Does a subarray with more than k odd elements count, and may even elements remain inside a counted interval? ``` ### Boundary reminders The source has positive input values, but only their odd/even status matters.

Overview: Count Subarrays Containing Exactly k Odd Values. Return the number of nonempty contiguous subarrays of nums containing exactly k odd elements.

InMobi logo
InMobi
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return the number of nonempty contiguous subarrays of nums containing exactly k odd elements. Even elements may appear anywhere within those intervals.

class Solution {
public:
    int numberOfSubarrays(vector<int>& nums, int k);
};

Examples

Example 1:

Input: nums = [2,1,2,1,2], k = 2
Output: 4
Explanation: A valid interval starts at0 or1 and ends at3 or4, giving2*2 choices.

Example 2:

Input: nums = [1,2,1], k = 1
Output: 4
Explanation: The intervals are[1] at either end,[1,2],and[2,1].

Constraints

  • There are 1 to 50000 elements.
  • Each nums value is an integer in [1,100000] .
  • 1 <= k <= nums.length .

Contract considerations

The source has positive input values, but only their odd/even status matters.

Boundary reminders

The source has positive input values, but only their odd/even status matters.