The main idea is to use a sliding window to keep track of the current subarray and count of odd numbers. If the count of odd numbers becomes more than k, move the start pointer to decrease the count. For every suitable subarray, calculate the number of possible subarrays that end at the current end pointer. This way, we can efficiently count the nice subarrays.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(n) for the dictionary to store prefix counts.
1#include <unordered_map>
2using namespace std;
3
4class Solution {
5public:
6 int numberOfSubarrays(vector<int>& nums, int k) {
7 int result = 0, oddCount = 0;
8 unordered_map<int, int> prefixCount;
9 prefixCount[0] = 1;
10
11 for (int num : nums) {
12 if (num % 2 == 1) {
13 oddCount++;
14 }
15 if (prefixCount.find(oddCount - k) != prefixCount.end()) {
16 result += prefixCount[oddCount - k];
17 }
18 prefixCount[oddCount]++;
19 }
20
21 return result;
22 }
23};
This C++ solution mirrors the Python solution by using an unordered_map to manage prefix counts of odd numbers. With this map, we can efficiently determine the count of nice subarrays as we iterate through the nums array.
This approach involves checking every possible subarray of nums and counting the odd numbers in each. If a subarray contains exactly k odd numbers, it is counted as nice. While straightforward to implement, this method is not efficient for large arrays as its time complexity is quadratic.
Time Complexity: O(n^2), where n is the length of nums.
Space Complexity: O(1)
1public class Solution {
2 public int NumberOfSubarrays(int[] nums, int k) {
3 int count = 0;
4 for (int start = 0; start < nums.Length; start++) {
5 int oddCount = 0;
6 for (int end = start; end < nums.Length; end++) {
7 if (nums[end] % 2 != 0) {
8 oddCount++;
9 }
10 if (oddCount == k) {
11 count++;
12 } else if (oddCount > k) {
13 break;
14 }
15 }
16 }
17 return count;
18 }
19}
The C# implementation also employs nested loops to inspect all subarrays and count the total number fitting the nice criteria. While direct and complete, caution against large input sizes due to quadratic time complexity.