You are given an array 'arr' of 'N' integers. Your task is to return the total number of distinct subarrays of 'arr' having 'k' odd elements.
If arr = [3,2,3], and k = 1
then there are 4 subarrays with 1 odd elements:
[3], [3,2], [2,3] & [3].
The first line contains single space-separated two integers 'N' and 'k'.
The second line contains 'N' space-separated integers, denoting the elements of array 'arr'.
Output format :
The output contains the number of distinct subarrays with 'k' odd elements.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
5 2
2 1 1 1 4
4
Following are 3 valid subarray:
[2,1,1], [1,1], [1,1], [1,1,4].
3 2
1 3 1
2
1 <= N <= 10^4
0 <= k <= N
1 <= arr[i] <= 10 ^ 5
Time Limit: 1sec
Approach is similar to “subarray sum equals k”.
Approach:
The idea is to maintain a count of odd numbers encountered so far and use a hashmap to keep track of frequency of different counts. This approach is similar to the approach used in finding subarray of sum k.
Algorithm:
function distinctSubKOdds(arr, k):
O(N ), where ‘N’ is the length of the given array.
The reason for this linear time complexity is that we only traverse the array once using a single loop. Within the loop, all the operations like incrementing counters, hashmap lookups, and updates take constant time.
O(N ), where ‘N’ is the length of the given array.
The space usage comes from the hashmap 'mp' that stores the count of odd numbers encountered. In the worst case, if all elements in the array are distinct and odd, the hashmap can contain ‘N’ unique keys (one for each element).