Count the Number of Good Subarrays — LeetCode 2537 Python Solution

MediumArrayHash TableSliding Window
Problem
#2537
Reading time
3 min

The problem

Given an integer array nums and an integer k, return the number of good subarrays of nums. A subarray arr is good if there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j].

Example

Input
nums = [1,1,1,1,1], k = 10
Output
1
Explanation
The only good subarray is the array nums itself.

Python solution

Python
class Solution:
    def countGood(self, nums: List[int], k: int) -> int:
        cnt = Counter()
        ans = cur = 0
        i = 0
        for x in nums:
            cur += cnt[x]
            cnt[x] += 1
            while cur - cnt[nums[i]] + 1 >= k:
                cnt[nums[i]] -= 1
                cur -= cnt[nums[i]]
                i += 1
            if cur >= k:
                ans += i + 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the array \textit{nums} auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2537. Count the Number of Good 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 2537. Count the Number of Good Subarrays?
LeetCode 2537. Count the Number of Good Subarrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 2537. Count the Number of Good Subarrays?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2537. Count the Number of Good Subarrays?
The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
What topics does LeetCode 2537. Count the Number of Good Subarrays cover?
LeetCode 2537. Count the Number of Good Subarrays is tagged Array, Hash Table 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