Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
Unknown
Space
O(1)
Unknown
💡

Intuition

Time UnknownSpace Unknown

The optimal approach uses a sliding window technique combined with a prefix sum to efficiently count the number of nice subarrays. This method allows us to find the count of subarrays with exactly k odd numbers by leveraging the count of subarrays with at most k odd numbers.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a helper function to count subarrays with at most k odd numbers.
  2. 2Step 2: Use this helper function to find the count of subarrays with at most k odd numbers and at most k-1 odd numbers.
  3. 3Step 3: The result is the difference between the two counts.
solution.py14 lines
1def countNiceSubarrays(nums, k):
2    def atMostK(k):
3        count = 0
4        left = 0
5        for right in range(len(nums)):
6            if nums[right] % 2 != 0:
7                k -= 1
8            while k < 0:
9                if nums[left] % 2 != 0:
10                    k += 1
11                left += 1
12            count += right - left + 1
13        return count
14    return atMostK(k) - atMostK(k - 1)

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.