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 i where nums1[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
K Divisible Elements Subarrays ProblemFind distinct subarrays with at most k elements divisible by p2332Input: nums=[2,3,3,2], k=2, p=3Step 1: Generate all subarraysStep 2: Count elements divisible by 3 in eachStep 3: Keep only subarrays with count ≤ 2Step 4: Remove duplicates using set[2]: 0 divisible[3]: 1 divisible[3,3]: 2 divisible[2,3]: 1 divisibleOutput: 11 distinct valid subarrays
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
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
32.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen