Open In App

Subarrays with k odd numbers

Last Updated : 24 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer array arr[] of size n, and an integer k. Your task is to find the number of contiguous subarrays in the array arr[], which contains exactly k odd numbers.

Examples : 

Input : arr = [2, 5, 6, 9],  k = 2 
Output: 2
Explanation: There are 2 subarrays with 2 odds: [2, 5, 6, 9] and [5, 6, 9].

Input : arr = [2, 2, 5, 6, 9, 2, 11],  k = 2
Output: 8
Explanation: There are 8 subarrays with 2 odds: [2, 2, 5, 6, 9], [2, 5, 6, 9], [5, 6, 9], [2, 2, 5, 6, 9, 2], [2, 5, 6, 9, 2], [5, 6, 9, 2], [6, 9, 2, 11] and [9, 2, 11] .

[Naive Approach] - Generate All Possible Subarrays - O(n ^ 2) Time and O(1) Space

The idea is to generate all possible subarrays, and find the count of subarrays with number of odd elements equal to k.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the count of subarrays with
// number of odd elements equal to k.
int countSubarrays(vector<int> &arr, int k) {
    int n = arr.size();
    int count = 0;

    // traverse for all
    // possible subarrays
    for (int i = 0; i < n; i++)  {

        int odd = 0;
        for (int j = i; j < n; j++) {

            // if current element is odd
            if (arr[j] % 2)
                odd++;

            // if count of odd numbers in
            // subarray is k
            if (odd == k)
                count++;
        }
    }
    return count;    
}

int main() {
    vector<int> arr = {2, 2, 5, 6, 9, 2, 11};
    int k = 2;
    cout << countSubarrays(arr, k);
    return 0;
}
Java
class GfG {

    // Function to find the count of subarrays with
    // number of odd elements equal to k.
    static int countSubarrays(int[] arr, int k) {
        int n = arr.length;
        int count = 0;

        // traverse for all
        // possible subarrays
        for (int i = 0; i < n; i++)  {

            int odd = 0;
            for (int j = i; j < n; j++) {

                // if current element is odd
                if (arr[j] % 2 != 0)
                    odd++;

                // if count of odd numbers in
                // subarray is k
                if (odd == k)
                    count++;
            }
        }
        return count;    
    }

    public static void main(String[] args) {
        int[] arr = {2, 2, 5, 6, 9, 2, 11};
        int k = 2;
        System.out.println(countSubarrays(arr, k));
    }
}
Python
# Function to find the count of subarrays with
# number of odd elements equal to k.
def countSubarrays(arr, k):
    n = len(arr)
    count = 0

    # traverse for all
    # possible subarrays
    for i in range(n):

        odd = 0
        for j in range(i, n):

            # if current element is odd
            if arr[j] % 2 != 0:
                odd += 1

            # if count of odd numbers in
            # subarray is k
            if odd == k:
                count += 1

    return count    

arr = [2, 2, 5, 6, 9, 2, 11]
k = 2
print(countSubarrays(arr, k))
C#
using System;
using System.Collections.Generic;

class GfG {

    // Function to find the count of subarrays with
    // number of odd elements equal to k.
    static int countSubarrays(List<int> arr, int k) {
        int n = arr.Count;
        int count = 0;

        // traverse for all
        // possible subarrays
        for (int i = 0; i < n; i++)  {

            int odd = 0;
            for (int j = i; j < n; j++) {

                // if current element is odd
                if (arr[j] % 2 != 0)
                    odd++;

                // if count of odd numbers in
                // subarray is k
                if (odd == k)
                    count++;
            }
        }
        return count;    
    }

    public static void Main() {
        List<int> arr = new List<int> {2, 2, 5, 6, 9, 2, 11};
        int k = 2;
        Console.WriteLine(countSubarrays(arr, k));
    }
}
JavaScript
// Function to find the count of subarrays with
// number of odd elements equal to k.
function countSubarrays(arr, k) {
    let n = arr.length;
    let count = 0;

    // traverse for all
    // possible subarrays
    for (let i = 0; i < n; i++)  {

        let odd = 0;
        for (let j = i; j < n; j++) {

            // if current element is odd
            if (arr[j] % 2 !== 0)
                odd++;

            // if count of odd numbers in
            // subarray is k
            if (odd === k)
                count++;
        }
    }
    return count;    
}

let arr = [2, 2, 5, 6, 9, 2, 11];
let k = 2;
console.log(countSubarrays(arr, k));

Output
8

[Expected Approach] - Using HashMap - O(n) Time and O(n) Space

The idea is to HashMap to store the count of prefix subarrays with particular number of odd numbers, and then calculate the subarrays with count of odd numbers equal to k using this HashMap. To do so, create HashMap prefix[], where prefix[i] stores the count of prefix subarrays with number of odd elements equal to i. When the count of odd numbers exceeds or is equal to k, add the number of prefixes which has "(odd - k)" numbers to the answer.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the count of subarrays with
// number of odd elements equal to k.
int countSubarrays(vector<int> &arr, int k) {
    int n = arr.size();
    int count = 0;

    // to store count of prefix subarrays
    // with particular count of odd numbers
    unordered_map<int, int> prefix;
    prefix[0] = 1;

    // to store count of odd numbers
    int odd = 0;

    for(int i = 0, odd = 0; i < n; i++) {

        // if current element is odd
        if (arr[i] % 2)
            odd++;
        
        // if count of odd numbers in
        // subarray is k
        if (prefix.count(odd - k) != 0)
            count += prefix[odd - k];

        prefix[odd]++;
    }
    return count;
}

int main() {
    vector<int> arr = {2, 2, 5, 6, 9, 2, 11};
    int k = 2;
    cout << countSubarrays(arr, k);
    return 0;
}
Java
import java.util.HashMap;

class GfG {

    // Function to find the count of subarrays with
    // number of odd elements equal to k.
    static int countSubarrays(int[] arr, int k) {
        int n = arr.length;
        int count = 0;

        // to store count of prefix subarrays
        // with particular count of odd numbers
        HashMap<Integer, Integer> prefix = new HashMap<>();
        prefix.put(0, 1);

        // to store count of odd numbers
        int odd = 0;

        for(int i = 0; i < n; i++) {

            // if current element is odd
            if (arr[i] % 2 != 0)
                odd++;
            
            // if count of odd numbers in
            // subarray is k
            if (prefix.containsKey(odd - k))
                count += prefix.get(odd - k);

            prefix.put(odd, prefix.getOrDefault(odd, 0) + 1);
        }
        return count;
    }

    public static void main(String[] args) {
        int[] arr = {2, 2, 5, 6, 9, 2, 11};
        int k = 2;
        System.out.println(countSubarrays(arr, k));
    }
}
Python
# Function to find the count of subarrays with
# number of odd elements equal to k.
def countSubarrays(arr, k):
    n = len(arr)
    count = 0

    # to store count of prefix subarrays
    # with particular count of odd numbers
    prefix = {0: 1}

    # to store count of odd numbers
    odd = 0

    for i in range(n):

        # if current element is odd
        if arr[i] % 2 != 0:
            odd += 1
        
        # if count of odd numbers in
        # subarray is k
        if (odd - k) in prefix:
            count += prefix[odd - k]

        prefix[odd] = prefix.get(odd, 0) + 1

    return count

arr = [2, 2, 5, 6, 9, 2, 11]
k = 2
print(countSubarrays(arr, k))
C#
using System;
using System.Collections.Generic;

class GfG {

    // Function to find the count of subarrays with
    // number of odd elements equal to k.
    static int countSubarrays(List<int> arr, int k) {
        int n = arr.Count;
        int count = 0;

        // to store count of prefix subarrays
        // with particular count of odd numbers
        Dictionary<int, int> prefix = new Dictionary<int, int>();
        prefix[0] = 1;

        // to store count of odd numbers
        int odd = 0;

        for(int i = 0; i < n; i++) {

            // if current element is odd
            if (arr[i] % 2 != 0)
                odd++;
            
            // if count of odd numbers in
            // subarray is k
            if (prefix.ContainsKey(odd - k))
                count += prefix[odd - k];

            if (prefix.ContainsKey(odd))
                prefix[odd]++;
            else
                prefix[odd] = 1;
        }
        return count;
    }

    public static void Main() {
        List<int> arr = new List<int> {2, 2, 5, 6, 9, 2, 11};
        int k = 2;
        Console.WriteLine(countSubarrays(arr, k));
    }
}
JavaScript
// Function to find the count of subarrays with
// number of odd elements equal to k.
function countSubarrays(arr, k) {
    let n = arr.length;
    let count = 0;

    // to store count of prefix subarrays
    // with particular count of odd numbers
    let prefix = {0: 1};

    // to store count of odd numbers
    let odd = 0;

    for (let i = 0, oddCount = 0; i < n; i++) {

        // if current element is odd
        if (arr[i] % 2 !== 0)
            oddCount++;
        
        // if count of odd numbers in
        // subarray is k
        if ((oddCount - k) in prefix)
            count += prefix[oddCount - k];

        prefix[oddCount] = (prefix[oddCount] || 0) + 1;
    }
    return count;
}

let arr = [2, 2, 5, 6, 9, 2, 11];
let k = 2;
console.log(countSubarrays(arr, k));

Output
8

[Alternate Approach] - Converting Odd and Even to 1 and 0 - O(n) Time and O(n) Space

The idea is to replace all the odd numbers with 1 and all the even numbers with zero and then calculate the number of subarrays with sum equal to m. Similar to above approach, use HashMap to store the sum at particular index, and proceed similarly.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the count of subarrays with
// number of odd elements equal to k.
int countSubarrays(vector<int> &arr, int k) {
    int n = arr.size();
    int count = 0;

    // to store count of prefix subarrays
    // with particular sum of elements
    unordered_map<int, int> prefix;
    prefix[0] = 1;

    // convert all odd numbers to 1
    // and even numbers to 0
    for (int i = 0; i < n; i++)
        arr[i] = arr[i] % 2;

    // to store sum of subarray
    int sum = 0;

    for(int i = 0; i < n; i++) {
        sum += arr[i];

        // if sum - k is present in prefix
        // then add prefix[sum - k] to count
        if (prefix.count(sum - k) != 0)
            count += prefix[sum - k];

        prefix[sum]++;
    }
    return count;
}

int main() {
    vector<int> arr = {2, 2, 5, 6, 9, 2, 11};
    int k = 2;
    cout << countSubarrays(arr, k);
    return 0;
}
Java
import java.util.HashMap;

class GfG {

    // Function to find the count of subarrays with
    // number of odd elements equal to k.
    static int countSubarrays(int[] arr, int k) {
        int n = arr.length;
        int count = 0;

        // to store count of prefix subarrays
        // with particular sum of elements
        HashMap<Integer, Integer> prefix = new HashMap<>();
        prefix.put(0, 1);

        // convert all odd numbers to 1
        // and even numbers to 0
        for (int i = 0; i < n; i++)
            arr[i] = arr[i] % 2;

        // to store sum of subarray
        int sum = 0;

        for(int i = 0; i < n; i++) {
            sum += arr[i];

            // if sum - k is present in prefix
            // then add prefix[sum - k] to count
            if (prefix.containsKey(sum - k))
                count += prefix.get(sum - k);

            prefix.put(sum, prefix.getOrDefault(sum, 0) + 1);
        }
        return count;
    }

    public static void main(String[] args) {
        int[] arr = {2, 2, 5, 6, 9, 2, 11};
        int k = 2;
        System.out.println(countSubarrays(arr, k));
    }
}
Python
# Function to find the count of subarrays with
# number of odd elements equal to k.
def countSubarrays(arr, k):
    n = len(arr)
    count = 0

    # to store count of prefix subarrays
    # with particular sum of elements
    prefix = {0: 1}

    # convert all odd numbers to 1
    # and even numbers to 0
    for i in range(n):
        arr[i] = arr[i] % 2

    # to store sum of subarray
    sum = 0

    for i in range(n):
        sum += arr[i]

        # if sum - k is present in prefix
        # then add prefix[sum - k] to count
        if (sum - k) in prefix:
            count += prefix[sum - k]

        prefix[sum] = prefix.get(sum, 0) + 1

    return count

arr = [2, 2, 5, 6, 9, 2, 11]
k = 2
print(countSubarrays(arr, k))
C#
using System;
using System.Collections.Generic;

class GfG {

    // Function to find the count of subarrays with
    // number of odd elements equal to k.
    static int countSubarrays(List<int> arr, int k) {
        int n = arr.Count;
        int count = 0;

        // to store count of prefix subarrays
        // with particular sum of elements
        Dictionary<int, int> prefix = new Dictionary<int, int>();
        prefix[0] = 1;

        // convert all odd numbers to 1
        // and even numbers to 0
        for (int i = 0; i < n; i++)
            arr[i] = arr[i] % 2;

        // to store sum of subarray
        int sum = 0;

        for(int i = 0; i < n; i++) {
            sum += arr[i];

            // if sum - k is present in prefix
            // then add prefix[sum - k] to count
            if (prefix.ContainsKey(sum - k))
                count += prefix[sum - k];

            if (prefix.ContainsKey(sum))
                prefix[sum]++;
            else
                prefix[sum] = 1;
        }
        return count;
    }

    public static void Main() {
        List<int> arr = new List<int> {2, 2, 5, 6, 9, 2, 11};
        int k = 2;
        Console.WriteLine(countSubarrays(arr, k));
    }
}
JavaScript
// Function to find the count of subarrays with
// number of odd elements equal to k.
function countSubarrays(arr, k) {
    let n = arr.length;
    let count = 0;

    // to store count of prefix subarrays
    // with particular sum of elements
    let prefix = {0: 1};

    // convert all odd numbers to 1
    // and even numbers to 0
    for (let i = 0; i < n; i++)
        arr[i] = arr[i] % 2;

    // to store sum of subarray
    let sum = 0;

    for (let i = 0; i < n; i++) {
        sum += arr[i];

        // if sum - k is present in prefix
        // then add prefix[sum - k] to count
        if ((sum - k) in prefix)
            count += prefix[sum - k];

        prefix[sum] = (prefix[sum] || 0) + 1;
    }
    return count;
}

let arr = [2, 2, 5, 6, 9, 2, 11];
let k = 2;
console.log(countSubarrays(arr, k));

Output
8

[Optimal Approach] - Using Subarrays with K - 1 Odds - O(n) Time and O(1)

The idea is to find the count of subarrays with at most k and k - 1 odd elements, then subtract the results to get the count of subarrays with exactly k odd elements. To find count of subarrays with at most x odd elements, run a loop from 0, and for each odd element, increment the counter count by 1. If count > k, then move the second pointer from 0, until count > k, store the length of subarray.

C++
#include <bits/stdc++.h>
using namespace std;

// to find count of subarrays with 
// at most x odd elements
int atMostX(vector<int> &arr, int x){
    int n = arr.size();

    // to store count of odd elements
    int odd = 0;

    // to store the results
    int ans = 0;

    // to mark the start of the subarray
    int start = 0;

    for(int i = 0; i < n; i++) {

        // if current element is odd
        if (arr[i] % 2)
            odd++;

        // if count of odd elements is greater than x
        // then remove elements from the start
        while (odd > x) {
            if (arr[start] % 2)
                odd--;
            start++;
        }

        // add the number of subarrays with at most x
        // odd elements ending at the current index
        ans += i - start + 1;
    }

    return ans;
}

// Function to find the count of subarrays with
// number of odd elements equal to k.
int countSubarrays(vector<int> &arr, int k) {
    int n = arr.size();

    // find count of subarrays with at most
    // k and k - 1 odd elements
    int x = atMostX(arr, k);
    int y = atMostX(arr, k - 1);

    return x - y;
}

int main() {
    vector<int> arr = {2, 2, 5, 6, 9, 2, 11};
    int k = 2;
    cout << countSubarrays(arr, k);
    return 0;
}
Java
import java.util.*;

class GfG {

    // to find count of subarrays with 
    // at most x odd elements
    static int atMostX(int[] arr, int x) {
        int n = arr.length;
        
        // to store count of odd elements
        int odd = 0;
        
        // to store the results
        int ans = 0;
        
        // to mark the start of the subarray
        int start = 0;
        
        for (int i = 0; i < n; i++) {
            
            // if current element is odd
            if (arr[i] % 2 != 0)
                odd++;
            
            // if count of odd elements is greater than x
            // then remove elements from the start
            while (odd > x) {
                if (arr[start] % 2 != 0)
                    odd--;
                start++;
            }
            
            // add the number of subarrays with at most x
            // odd elements ending at the current index
            ans += i - start + 1;
        }
        
        return ans;
    }
    
    // Function to find the count of subarrays with
    // number of odd elements equal to k.
    static int countSubarrays(int[] arr, int k) {
        int n = arr.length;
        
        // find count of subarrays with at most
        // k and k - 1 odd elements
        int x = atMostX(arr, k);
        int y = atMostX(arr, k - 1);
        
        return x - y;
    }
    
    public static void main(String[] args) {
        int[] arr = {2, 2, 5, 6, 9, 2, 11};
        int k = 2;
        System.out.println(countSubarrays(arr, k));
    }
}
Python
# to find count of subarrays with 
# at most x odd elements
def atMostX(arr, x):
    n = len(arr)
    
    # to store count of odd elements
    odd = 0
    
    # to store the results
    ans = 0
    
    # to mark the start of the subarray
    start = 0
    
    for i in range(n):
        
        # if current element is odd
        if arr[i] % 2 != 0:
            odd += 1
        
        # if count of odd elements is greater than x
        # then remove elements from the start
        while odd > x:
            if arr[start] % 2 != 0:
                odd -= 1
            start += 1
        
        # add the number of subarrays with at most x
        # odd elements ending at the current index
        ans += i - start + 1
    
    return ans

# Function to find the count of subarrays with
# number of odd elements equal to k.
def countSubarrays(arr, k):
    n = len(arr)
    
    # find count of subarrays with at most
    # k and k - 1 odd elements
    x = atMostX(arr, k)
    y = atMostX(arr, k - 1)
    
    return x - y

if __name__ == "__main__":
    arr = [2, 2, 5, 6, 9, 2, 11]
    k = 2
    print(countSubarrays(arr, k))
C#
using System;
using System.Collections.Generic;

class GfG {

    // to find count of subarrays with 
    // at most x odd elements
    static int atMostX(List<int> arr, int x) {
        int n = arr.Count;
        
        // to store count of odd elements
        int odd = 0;
        
        // to store the results
        int ans = 0;
        
        // to mark the start of the subarray
        int start = 0;
        
        for (int i = 0; i < n; i++) {
            
            // if current element is odd
            if (arr[i] % 2 != 0)
                odd++;
            
            // if count of odd elements is greater than x
            // then remove elements from the start
            while (odd > x) {
                if (arr[start] % 2 != 0)
                    odd--;
                start++;
            }
            
            // add the number of subarrays with at most x
            // odd elements ending at the current index
            ans += i - start + 1;
        }
        
        return ans;
    }

    // Function to find the count of subarrays with
    // number of odd elements equal to k.
    static int countSubarrays(List<int> arr, int k) {
        int n = arr.Count;
        
        // find count of subarrays with at most
        // k and k - 1 odd elements
        int x = atMostX(arr, k);
        int y = atMostX(arr, k - 1);
        
        return x - y;
    }

    public static void Main() {
        List<int> arr = new List<int> {2, 2, 5, 6, 9, 2, 11};
        int k = 2;
        Console.WriteLine(countSubarrays(arr, k));
    }
}
JavaScript
// to find count of subarrays with 
// at most x odd elements
function atMostX(arr, x) {
    let n = arr.length;
    
    // to store count of odd elements
    let odd = 0;
    
    // to store the results
    let ans = 0;
    
    // to mark the start of the subarray
    let start = 0;
    
    for (let i = 0; i < n; i++) {
        
        // if current element is odd
        if (arr[i] % 2 !== 0)
            odd++;
        
        // if count of odd elements is greater than x
        // then remove elements from the start
        while (odd > x) {
            if (arr[start] % 2 !== 0)
                odd--;
            start++;
        }
        
        // add the number of subarrays with at most x
        // odd elements ending at the current index
        ans += i - start + 1;
    }
    
    return ans;
}

// Function to find the count of subarrays with
// number of odd elements equal to k.
function countSubarrays(arr, k) {
    let n = arr.length;
    
    // find count of subarrays with at most
    // k and k - 1 odd elements
    let x = atMostX(arr, k);
    let y = atMostX(arr, k - 1);
    
    return x - y;
}

let arr = [2, 2, 5, 6, 9, 2, 11];
let k = 2;
console.log(countSubarrays(arr, k));

Output
8

Article Tags :
Practice Tags :

Similar Reads