K Divisible Elements Subarrays - Problem
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
iwherenums1[i] != nums2[i].
A subarray is defined as a non-empty contiguous sequence of elements in an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,3,3,2], k = 2, p = 3
›
Output:
11
💡 Note:
Subarrays with at most 2 elements divisible by 3: [2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3], [3,2], [2]. After removing duplicates: [2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,2] = 8 distinct subarrays.
Example 2 — All Valid
$
Input:
nums = [1,2,3,4], k = 4, p = 1
›
Output:
10
💡 Note:
All elements divisible by 1, k=4 allows all. All 10 possible subarrays are valid: [1], [1,2], [1,2,3], [1,2,3,4], [2], [2,3], [2,3,4], [3], [3,4], [4].
Example 3 — No Divisible Elements
$
Input:
nums = [1,9,8,3], k = 1, p = 2
›
Output:
10
💡 Note:
No elements divisible by 2, so all subarrays are valid: [1], [1,9], [1,9,8], [1,9,8,3], [9], [9,8], [9,8,3], [8], [8,3], [3] = 10 distinct.
Constraints
- 1 ≤ nums.length ≤ 200
- 1 ≤ nums[i] ≤ 200
- 1 ≤ k ≤ nums.length
- 1 ≤ p ≤ 200
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums=[2,3,3,2], k=2, p=3
2
Process
Generate all subarrays, count divisible by p
3
Output
Count distinct valid subarrays
Key Takeaway
🎯 Key Insight: Use sets to automatically handle uniqueness while tracking divisible element counts
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code