Count Number of Nice Subarrays — LeetCode 1248 Python Solution

MediumArrayHash TableMathPrefix SumSliding Window
Problem
#1248
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview