#3729
Count Distinct Subarrays Divisible by K in Sorted Array
HardArrayHash TablePrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using prefix sums and a hash map allows us to efficiently track sums and their remainders, reducing the need to check each subarray individually.
⚙️
Algorithm
3 steps- 1Step 1: Calculate prefix sums and their remainders when divided by k.
- 2Step 2: Use a hash map to track the frequency of each remainder.
- 3Step 3: For each unique value, count distinct subarrays based on the prefix sums and their remainders.
solution.py10 lines
1def countDistinct(nums, k):
2 prefix_sum = 0
3 count = 0
4 prefix_count = {0: 1}
5 for num in nums:
6 prefix_sum += num
7 remainder = prefix_sum % k
8 count += prefix_count.get(remainder, 0)
9 prefix_count[remainder] = prefix_count.get(remainder, 0) + 1
10 return countℹ
Complexity note: The time complexity is O(n) due to a single pass through the array. Space complexity is O(n) for the hash map storing remainders.
- 1Distinct subarrays can be counted using prefix sums and remainders.
- 2Using a hash map optimizes the counting process.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.