짬뽕얼큰하게의 맨땅에 헤딩 :: Count of Interesting Subarrays

Leetcode Problem:

Summary

  • This problem requires finding the count of subarrays that satisfy a certain condition based on the modulo and k.

Approach

  • The solution uses a sliding window approach and a hashmap to keep track of the prefix sum and the count of interesting subarrays.

Complexity

  • O(n)

Explanation

  • The solution initializes a hashmap to store the prefix sum and its count
  • It then iterates over the array, updating the prefix sum and the count of interesting subarrays
  • The count of interesting subarrays is updated by adding the count of subarrays that end at the current position and have a prefix sum that satisfies the condition
  • The solution returns the total count of interesting subarrays.

Solution Code:


class Solution {
public:
    long long countInterestingSubarrays(vector& nums, int modulo, int k) {
        int n = nums.size();
        unordered_map cnt;
        long long res = 0;
        int prefix = 0;
        cnt[0] = 1;
        for (int i = 0; i < n; i++) {
            prefix += nums[i] % modulo == k;
            res += cnt[(prefix - k + modulo) % modulo];
            cnt[prefix % modulo]++;
        }
        return res;
    }
};

'알고리즘' 카테고리의 다른 글

Count Subarrays of Length Three With a Condition  (1) 2025.04.27
Count Subarrays With Fixed Bounds  (0) 2025.04.26
Count Complete Subarrays in an Array  (0) 2025.04.24
Count Largest Group  (0) 2025.04.23
Count the Number of Ideal Arrays  (1) 2025.04.22
블로그 이미지

짬뽕얼큰하게

,