712148. Count Subarray with k odds
Here is a detailed Markdown blog post for the GeeksforGeeks problem "Count Subarray with k odds":
Count Subarray with k odds
Summary
Given an array of integers, count the number of subarrays that have exactly k odd numbers. This problem involves using prefix sums to efficiently calculate the number of odd numbers in a subarray.
Detailed Explanation
To solve this problem, we will use a two-pointer approach along with prefix sums. Let's consider a simple example: suppose we want to find all subarrays that have exactly 2 odd numbers. We can start by calculating the total count of odd numbers in the array using a prefix sum array. Then, we iterate over the array and maintain two pointers, start and end, which represent the current subarray. For each position in the array, we calculate the number of odd numbers in the subarray [start, end] by subtracting the previous prefix sum from the current prefix sum. If this count equals k, we increment our result.
Here's a step-by-step breakdown:
- Calculate the total count of odd numbers in the array using a prefix sum array.
- Initialize two pointers,
startandend, to 0. - Iterate over the array:
- For each position, calculate the number of odd numbers in the subarray
[start, end]by subtracting the previous prefix sum from the current prefix sum. - If this count equals
k, increment our result. - Update
startandendaccordingly to consider the next subarray.
- For each position, calculate the number of odd numbers in the subarray
- Return the total count of subarrays with exactly
kodd numbers.
Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we only need a constant amount of space for the prefix sum array and pointers.
Optimized Solutions
Java
public int countSubarrays(int[] arr, int k) {
int n = arr.length;
boolean[] odd = new boolean[n];
for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0) {
odd[i] = true;
}
}
int count = 0;
int start = 0, end = 0;
int oddCount = 0;
while (end < n) {
if (!odd[end]) {
if (oddCount == k) {
count++;
}
oddCount--;
} else {
oddCount++;
}
end++;
}
return count;
}