Skip to content
LC-2845 Medium LeetCode

2845. Count of Interesting Subarrays

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 58% Topics: Array, Hash Table, Prefix Sum
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(m)

import collections


# freq table, prefix sum
class Solution(object):
    def countInterestingSubarrays(self, nums, modulo, k):
        """
        :type nums: List[int]
        :type modulo: int
        :type k: int
        :rtype: int
        """
        cnt = collections.Counter([0])
        result = prefix = 0
        for x in nums:
            if x%modulo == k:
                prefix = (prefix+1)%modulo
            result += cnt[(prefix-k)%modulo]
            cnt[prefix] += 1
        return result

Solution from kamyu104/LeetCode-Solutions · MIT