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: 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
K Divisible Elements Subarrays Rolling Hash Optimization Approach INPUT nums array: 2 i=0 3 i=1 3 i=2 2 i=3 Red = divisible by p Parameters: k = 2 (max divisible) p = 3 (divisor) Find distinct subarrays with at most k elements divisible by p Total subarrays: n(n+1)/2 = 10 ALGORITHM STEPS 1 Generate Subarrays Iterate all start/end pairs 2 Count Divisibles Track nums[i] % p == 0 3 Filter by k Keep if count <= k 4 Rolling Hash Use hash for uniqueness Valid Subarrays (div count): [2] (0) OK [2,3] (1) OK [2,3,3] (2) OK [2,3,3,2] (2) OK [3] (1) OK [3,3] (2) OK [3,3,2] (2) OK [3,2] (1) OK [2] (0) dup! [3] (1) dup! Unique: 11 FINAL RESULT Distinct Subarrays 11 Breakdown: Length 1: 3 distinct Length 2: 4 distinct Length 3: 3 distinct Length 4: 1 distinct Verification: All subarrays have at most 2 elements divisible by 3 - OK Key Insight: Rolling Hash enables O(1) subarray comparison by computing unique hash values incrementally. hash(subarray) = sum(element * base^position) mod large_prime. This transforms O(n^3) string comparison to O(n^2) time. Use HashSet to track distinct valid subarrays efficiently. TutorialsPoint - K Divisible Elements Subarrays | Rolling Hash Optimization Time: O(n^2) | Space: O(n^2)
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