Sliding Window: Subarrays with k odd numbers

Problem Statement:

Subarrays with k odd numbers

Example:

 

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

Output: 2

Solution Explanation:

We will take 2 pointers l and r.

l will shrinks the window

r expands the window towards right,

When odd number is detected, decrement k,

When k == 0, window has exactly required number of odds.

“count” will have how many valid subarray at end of r.

Time Complexity: O(n)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;


int solution(vector<int>& nums, int k) 
{
    int res = 0, count = 0;

    for (int l = 0, r = 0; r < nums.size(); r++)
    {
        if (nums[r] % 2)
        {
            k--;
            count = 0;
        }
        while (k == 0)
        {
            count++;
            k += (nums[l++] % 2);
        }
        res += count;
    }
    return res;
}


int main() 
{
    vector<int> arr = {1,1,2,1,1};
    int k = 3;
    cout << solution(arr, k);
    return 0;
}

Output

2
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *