2537. Count-The-Number-Of-Good-Subarrays

Question Link

Difficulty: Medium

Classic sliding window problem… We keep track of the number of pairs within our current window (to do this we want to keep track of the count of each element inside the window). Until our current window is valid, we keep expanding our window by moving our right pointer forwards. While our current window is valid, we can keep moving our left pointer forwards, shrinking our window and calculating the number of subarrays that were valid given l and r.

For updates:

class Solution(object):
    def countGood(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        n = len(nums)
        l = 0
        r = 0
        res = 0

        count = {}
        no_of_pairs = 0
        for l in range(n):
            while no_of_pairs < k and r < n:
                if nums[r] not in count:
                    count[nums[r]] = 1
                else:
                    no_of_pairs += count[nums[r]]
                    count[nums[r]] += 1
                r += 1

            if no_of_pairs >= k:
                res += n - (r - 1)
            count[nums[l]] -= 1
            no_of_pairs -= count[nums[l]]

        return res

Time Complexity: O(n)

Space Complexity: O(n)

Time Taken: 14m 51s