2339. K Divisible Elements Subarrays
My accepted Python solution to LeetCode problem 2339, K Divisible Elements Subarrays, running in 395ms.
- Difficulty: Medium
- Python
- Runtime 395ms
- Memory 31.7MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 395ms, memory 31.7MB, accepted 2026-01-02.
class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
seen = set()
n = len(nums)
for i in range(n):
count = 0
for j in range(i, n):
if nums[j] % p == 0:
count += 1
if count > k:
break
seen.add(tuple(nums[i:j+1]))
return len(seen)