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.
1import java.util.HashMap;
2
3public class Solution {
4 public int numberOfSubarrays(int[] nums, int k) {
5 int count = 0, oddCount = 0, result = 0;
6 HashMap<Integer, Integer> prefixCount = new HashMap<>();
7 prefixCount.put(0, 1);
8
9 for (int num : nums) {
10 if (num % 2 == 1) {
11 oddCount++;
12 }
13 if (prefixCount.containsKey(oddCount - k)) {
14 result += prefixCount.get(oddCount - k);
15 }
16 prefixCount.put(oddCount, prefixCount.getOrDefault(oddCount, 0) + 1);
17 }
18
19 return result;
20 }
21}
Like the Python solution, this Java solution uses a HashMap to count the frequency of odd counts (prefix counts). We iterate over nums, updating the count of odd numbers, and use the HashMap to track previously seen odd counts. If a previously seen odd count matches the current count minus k, it contributes to the number of nice subarrays.
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)
1def number_of_subarrays(nums, k):
2 count = 0
3 for start in range(len(nums)):
4 odd_count = 0
5 for end in range(start, len(nums)):
6 if nums[end] % 2 == 1:
7 odd_count += 1
8 if odd_count == k:
9 count += 1
10 elif odd_count > k:
11 break
12 return count
This Python solution iterates over all possible subarrays starting from each index. For each subarray, it counts the number of odd numbers and checks if this matches k. If matched, the count of nice subarrays is incremented.