Problem
Given an integer array nums and two integers k and p, return the number ofdistinct 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
iwherenums1[i] != nums2[i].
A subarray is defined as a non-empty contiguous sequence of elements in an array.
Examples
Example 1
| |
Example 2
| |
Constraints
1 <= nums.length <= 2001 <= nums[i], p <= 2001 <= k <= nums.length
Follow up:
Can you solve this problem in O(n2) time complexity?
Solution
Method 1 – Hash Set with Sliding Window
Intuition
We want to count the number of distinct subarrays with at most k elements divisible by p. By using a sliding window and a hash set to store unique subarrays, we can efficiently enumerate all possible subarrays and check the divisibility condition.
Approach
- Initialize an empty set to store unique subarrays (as tuples).
- For each starting index
iinnums:- Initialize a counter for divisible elements.
- For each ending index
jfromito the end:- If
nums[j] % p == 0, increment the counter. - If the counter exceeds
k, break. - Otherwise, add the subarray
nums[i:j+1](as a tuple) to the set.
- If
- Return the size of the set.
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(n^2 * m)— n is the length of nums, m is the average subarray length (for hashing and storing subarrays). - 🧺 Space complexity:
O(n^2 * m)— For storing all unique subarrays.