Count Number of Nice Subarrays — LeetCode 1248 Python Solution
MediumArrayHash TableMathPrefix SumSliding Window
- Problem
- #1248
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Example
- 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].
Python solution
Python
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
cnt = Counter({0: 1})
ans = t = 0
for v in nums:
t += v & 1
ans += cnt[t - k]
cnt[t] += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1248. Count Number of Nice Subarrays is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
LeetCode 523Continuous Subarray SumMediumLeetCode 930Binary Subarrays With SumMediumLeetCode 1442Count Triplets That Can Form Two Arrays of Equal XORMediumLeetCode 1658Minimum Operations to Reduce X to ZeroMediumLeetCode 2875Minimum Size Subarray in Infinite ArrayMediumLeetCode 149Max Points on a LineHard
Frequently asked questions
- How hard is LeetCode 1248. Count Number of Nice Subarrays?
- LeetCode 1248. Count Number of Nice Subarrays is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1248. Count Number of Nice Subarrays?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1248. Count Number of Nice Subarrays?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1248. Count Number of Nice Subarrays cover?
- LeetCode 1248. Count Number of Nice Subarrays is tagged Array, Hash Table, Math, Prefix Sum and Sliding Window on LeetCode.