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:
i where nums1[i] != nums2[i].A subarray is defined as a non-empty contiguous sequence of elements in an array.
Example 1:
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.
Example 2:
Input: nums = [1,2,3,4], k = 4, p = 1 Output: 10 Explanation: All element of nums are divisible by p = 1. Also, every subarray of nums will have at most 4 elements that are divisible by 1. Since all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.
Constraints:
1 <= nums.length <= 2001 <= nums[i], p <= 2001 <= k <= nums.length
Follow up:
Can you solve this problem in O(n2) time complexity?
Problem Overview: Given an integer array nums, an integer k, and p, count the number of distinct subarrays where at most k elements are divisible by p. Two subarrays are considered the same if their sequences of values are identical.
The challenge has two parts: enforcing the constraint on divisible elements and ensuring only unique subarrays are counted. Straight enumeration works, but you must track uniqueness efficiently using hashing or a trie.
Approach 1: Brute Force with Set for Distinctions (O(n^2 * L) time, O(n^2) space)
Enumerate every possible subarray starting at index i. As you extend the subarray to the right, maintain a counter of numbers divisible by p. Once the counter exceeds k, stop extending that start index because any longer subarray will also violate the constraint. Each valid subarray is inserted into a hash set (typically as a tuple or encoded string) so duplicates are removed automatically.
This approach relies heavily on a array traversal and a hash table to track uniqueness. The main cost comes from storing and hashing subarray representations, which can take up to O(L) per insertion where L is the subarray length. Despite the quadratic enumeration, the early break when divisible elements exceed k prunes many cases.
Approach 2: Optimized Sliding Window with HashMap (O(n^2) time, O(n^2) space)
A more efficient implementation avoids repeatedly rebuilding subarray representations. Use a sliding expansion from each start index while maintaining the count of numbers divisible by p. Instead of storing raw subarrays, compute an incremental rolling hash for each extension and insert the hash into a set or hashmap.
Each time the window grows by one element, update the hash value using a polynomial rolling hash formula. This avoids copying the entire subarray and keeps insertion close to constant time. The window stops expanding once the divisible count exceeds k. Because hashes represent subarrays uniquely with very high probability, duplicates are filtered efficiently.
This approach combines enumeration with hashing techniques similar to substring problems. It leverages ideas from hash tables and structures like a trie, which can also store subarray prefixes without duplication.
Recommended for interviews: Start with the brute-force enumeration to show you understand how to enforce the k divisible constraint. Interviewers typically expect you to optimize the uniqueness check using hashing (or a trie). The optimized hashing approach demonstrates stronger algorithmic thinking and reduces overhead from repeatedly copying subarrays.
In this approach, we generate all possible subarrays of the input array using two nested loops. For each subarray, we count the number of elements divisible by `p`. If the count is less than or equal to `k`, we add the subarray as a tuple to a set to ensure distinctness. Finally, the size of the set gives us the required count of distinct subarrays.
This solution uses two nested loops to generate all subarrays and counts the number of elements divisible by p. A set is used to store each subarray uniquely.
Python
JavaScript
C++
Java
C#
Time Complexity: O(n^3) due to nested loops and set operations.
Space Complexity: O(n^2) due to the storage of subarrays in the set.
This approach optimizes the subarray generation process using a sliding window technique. We utilize a hashmap to keep track of subarray counts, efficiently managing the addition and removal of elements to/from the subarray as we slide the window.
The optimized sliding window approach generates subarrays by extending one end while counting divisible elements with adjustable starting points, skipping further extensions if conditions are not met.
Python
JavaScript
C++
Java
C#
Time Complexity: O(n^2) since subarrays are handled more efficiently compared to the brute-force approach.
Space Complexity: O(n^2) for distinct subarray storage in sets.
We can enumerate the left endpoint i of the subarray, and then enumerate the right endpoint j in the range [i, n). During the enumeration of the right endpoint, we use double hashing to store the hash value of the subarray into a set. Finally, we return the size of the set.
The time complexity is O(n^2), and the space complexity is O(n^2). Here, n is the length of the array.
Python
Java
C++
Go
TypeScript
Python
| Approach | Complexity |
|---|---|
| Brute Force with Set for Distinctions | Time Complexity: O(n^3) due to nested loops and set operations. Space Complexity: O(n^2) due to the storage of subarrays in the set. |
| Optimized Sliding Window with HashMap | Time Complexity: O(n^2) since subarrays are handled more efficiently compared to the brute-force approach. Space Complexity: O(n^2) for distinct subarray storage in sets. |
| Enumeration + String Hashing | — |
| Default Approach | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force with Set for Distinctions | O(n^2 * L) | O(n^2) | Simple implementation when constraints are moderate and clarity is preferred |
| Optimized Sliding Window with HashMap (Rolling Hash) | O(n^2) | O(n^2) | Best practical approach to reduce subarray copying and speed up uniqueness checks |
K Divisible Elements Subarrays | Leetcode 2261 | Maps | Contest 291 🔥🔥 • Coding Decoded • 4,275 views views
Watch 9 more video solutions →Practice K Divisible Elements Subarrays with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor