![]() |
VOOZH | about |
Given an integer array arr[] of size n, and a target integer k. Determine the number of contiguous subarrays (i.e., continuous segments of the array) that contain exactly k odd numbers.
A subarray is defined as a non-empty sequence of consecutive elements from the array.
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] .
Table of Content
The idea is to generate all possible subarrays, and find the count of subarrays with number of odd elements equal to k.
8
The idea is to use a HashMap to track the frequency of prefix subarrays with a given count of odd numbers. For each element, maintain a running count of odd numbers seen so far. If the current odd count is at least
k, then the number of subarrays ending at the current index with exactlykodd numbers is equal toprefix[odd - k]. Update the prefix count map as you iterate through the array.
8
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.
Step by Step Implementation
8