Count of Interesting Subarrays - Problem

You are given a 0-indexed integer array nums, an integer modulo, and an integer k.

Your task is to find the count of subarrays that are interesting.

A subarray nums[l..r] is interesting if the following condition holds:

  • Let cnt be the number of indices i in the range [l, r] such that nums[i] % modulo == k. Then, cnt % modulo == k.

Return an integer denoting the count of interesting subarrays.

Note: A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,4], modulo = 3, k = 1
Output: 3
💡 Note: Subarrays: [4] has 1 element where 4%3=1, and 1%3=1 ✓. [2,4] has 1 element where 4%3=1, and 1%3=1 ✓. [3,2,4] has 1 element where 4%3=1, and 1%3=1 ✓. Total: 3 interesting subarrays.
Example 2 — Multiple Valid Elements
$ Input: nums = [2,4,2,2,5,2], modulo = 3, k = 2
Output: 4
💡 Note: Looking for elements where nums[i]%3=2: positions 0,2,3,5 have value 2. We need subarrays where count%3=2. Subarrays with exactly 2 or 5 such elements work.
Example 3 — No Valid Subarrays
$ Input: nums = [1,2,3], modulo = 4, k = 3
Output: 0
💡 Note: No element satisfies nums[i]%4=3, so no subarray can have count%4=3. Result is 0.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109
  • 1 ≤ modulo ≤ 109
  • 0 ≤ k < modulo

Visualization

Tap to expand
Count of Interesting Subarrays INPUT nums array: 3 i=0 2 i=1 4 i=2 nums[i] % 3 == 1 ? 3%3=0 NO 2%3=2 NO 4%3=1 OK Parameters: modulo = 3 k = 1 Find subarrays where cnt % modulo == k ALGORITHM STEPS 1 Prefix Sum Track cnt of matching elements modulo k 2 Hash Map Store prefix % mod frequencies 3 Count Pairs Find (pre-k) % mod in hash map 4 Accumulate Sum all valid pairs Hash Map State: prefix % 3 count 0 1 (init) 1 2 2 0 FINAL RESULT 3 Interesting Subarrays Valid Subarrays: [3] cnt=0, 0%3=0 != 1 [3,2] cnt=0, 0%3 != 1 [3,2,4] cnt=1, 1%3=1 OK [4] cnt=1, 1%3=1 OK [2,4] and [2] also checked Key Insight: Use prefix sum with modular arithmetic: For subarray [l,r], cnt = prefix[r] - prefix[l-1]. We need (prefix[r] - prefix[l-1]) % mod == k, which means prefix[l-1] % mod == (prefix[r] - k) % mod. Hash map stores counts of each prefix % mod value, allowing O(1) lookup for valid pairs. Time: O(n), Space: O(n). TutorialsPoint - Count of Interesting Subarrays | Hash Map Approach
Asked in
Google 12 Microsoft 8 Amazon 6
12.5K Views
Medium Frequency
~25 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen