Leetcode #2261: K Divisible Elements Subarrays
In this guide, we solve Leetcode #2261 K Divisible Elements Subarrays in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an integer array nums and two integers k and p, return the number of distinct subarrays, which have at most k elements that are divisible by p. Two arrays nums1 and nums2 are said to be distinct if: They are of different lengths, or There exists at least one index i where nums1[i] != nums2[i].
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Trie, Array, Hash Table, Enumeration, Hash Function, Rolling Hash
Intuition
Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.
By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.
Approach
Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.
This keeps the solution linear while remaining easy to explain in an interview setting.
Steps:
- Initialize a hash map for seen items or counts.
- Iterate through the input, querying/updating the map.
- Return the first valid result or the final computed value.
Example
Input: nums = [2,3,3,2,2], k = 2, p = 2
Output: 11
Explanation:
The elements at indices 0, 3, and 4 are divisible by p = 2.
The 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:
[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].
Note that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.
The subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.
Python Solution
class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
s = set()
n = len(nums)
base1, base2 = 131, 13331
mod1, mod2 = 10**9 + 7, 10**9 + 9
for i in range(n):
h1 = h2 = cnt = 0
for j in range(i, n):
cnt += nums[j] % p == 0
if cnt > k:
break
h1 = (h1 * base1 + nums[j]) % mod1
h2 = (h2 * base2 + nums[j]) % mod2
s.add(h1 << 32 | h2)
return len(s)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.