Problem Description
Given an array of integers nums and an integer k, a continuous subarray is called nice if there are exactly k odd numbers in it. The task is to determine the number of such nice subarrays.
Key Insights
- Convert the problem to counting subarrays with a specific "prefix sum" value where the sum represents the count of odd numbers.
- Use a hash table (or dictionary) to store the frequency of prefix sums encountered.
- The number of nice subarrays ending at the current index equals the frequency of (current prefix sum - k) seen so far.
- This approach allows you to find the answer in one pass over the array.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in nums, because we traverse the array once. Space Complexity: O(n), in the worst case where each prefix sum is unique and stored in the hash table.
Solution
We solve the problem using a prefix sum approach. First, we iterate through the array and convert it into a prefix sum representing the cumulative count of odd numbers encountered. As we compute the prefix sums, we use a hash table to record how many times each prefix sum appears. For every current prefix sum value, we check how many times we have seen a prefix sum equal to (current prefix sum - k). The idea is that if prefix[j] - prefix[i] equals k, then between indices i+1 and j, there are exactly k odd numbers. This gives us the count of valid subarrays ending at the current index.
This method works efficiently as it requires only a single pass through the array and maintains a running frequency count using the hash table.