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:
8
💡 Note:
Subarrays with at most 2 elements divisible by 3: Starting from index 0: [2], [2,3], [2,3,3], [2,3,3,2]. Starting from index 1: [3], [3,3], [3,3,2]. Starting from index 2: [3], [3,2]. Starting from index 3: [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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code