Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3 Output: 2 Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums = [2,4,6], k = 1 Output: 0 Explanation: There are no odd numbers in the array.
Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2 Output: 16
Constraints:
1 <= nums.length <= 500001 <= nums[i] <= 10^51 <= k <= nums.lengthThe 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.
This solution uses a hash map (dictionary) to count the frequency of certain odd counts (prefix counts). As we iterate over nums, we update the current count of odd numbers. If the current count minus k has been seen before, it means there is a subarray ending at the current position with exactly k odd numbers.
Java
C++
C#
JavaScript
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(n) for the dictionary to store prefix counts.
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.
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.
Java
C++
C#
JavaScript
Time Complexity: O(n^2), where n is the length of nums.
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Two-Pointer or Sliding Window Approach | Time Complexity: O(n), where n is the length of the array. |
| Brute Force Approach | Time Complexity: O(n^2), where n is the length of nums. |
L10. Count number of Nice subarrays | 2 Pointers and Sliding Window Playlist • take U forward • 98,734 views views
Watch 9 more video solutions →Practice Count Number of Nice Subarrays with our built-in code editor and test cases.
Practice on FleetCode