Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 25, 2025 21:43
Show Gist options
  • Save Ifihan/b959a4131d3dab9f7e90be3b89f2c7d3 to your computer and use it in GitHub Desktop.
Save Ifihan/b959a4131d3dab9f7e90be3b89f2c7d3 to your computer and use it in GitHub Desktop.
Count of Interesting Subarrays

Question

Approach

To solve the problem, I kept track of how many numbers so far satisfy nums[i] % modulo == k using a prefix count. At each position, I calculated the current prefix modulo and checked how many previous prefix sums would form an interesting subarray ending at the current index. I used a hashmap to record the frequency of each prefix modulo. By rearranging the modulo condition, I quickly found how many matches existed without checking every subarray. I updated the answer at each step and continued this process across the array.

Implementation

class Solution:
    def countInterestingSubarrays(self, nums: List[int], modulo: int, k: int) -> int:
        prefix = 0
        count = defaultdict(int)
        count[0] = 1
        ans = 0

        for num in nums:
            if num % modulo == k:
                prefix += 1
            curr_mod = prefix % modulo
            target = (curr_mod - k + modulo) % modulo
            ans += count[target]
            count[curr_mod] += 1
        
        return ans

Complexities

  • Time:
  • Space:
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment