LeetCode 2916: Subarrays Distinct Element Sum of Squares II
Problem Description
Explanation
To solve this problem, we can use a sliding window technique combined with a data structure to efficiently calculate the distinct counts of subarrays. We can maintain a hashmap to keep track of the frequency of each element in the current window. As we slide the window, we update the distinct count of subarrays by adding the counts of new elements and subtracting the counts of elements leaving the window.
Here is the step-by-step approach:
- Initialize variables
result
to store the final answer andMOD
as 10^9 + 7. - Initialize an empty hashmap
count
to store the frequency of elements in the current window. - Initialize
left
andright
pointers for the sliding window technique. - Iterate over the array using the
right
pointer and update thecount
hashmap. - For each element added, update the
result
by adding the square of the current distinct count. - Move the
left
pointer while incrementing it and update thecount
hashmap accordingly. - Repeat steps 4-6 until
right
reaches the end of the array. - Finally, return the
result
moduloMOD
.
The time complexity of this approach is O(N) where N is the number of elements in the input array. The space complexity is O(N) due to the hashmap.
Solutions
class Solution {
public int sumOfDistancesInTree(int[] nums) {
long result = 0;
int MOD = 1000000007;
int left = 0, right = 0;
Map<Integer, Integer> count = new HashMap<>();
while (right < nums.length) {
count.put(nums[right], count.getOrDefault(nums[right], 0) + 1);
result = (result + count.keySet().size() * count.keySet().size()) % MOD;
while (left < right && count.get(nums[right]) > 1) {
count.put(nums[left], count.get(nums[left]) - 1);
if (count.get(nums[left]) == 0) {
count.remove(nums[left]);
}
left++;
}
right++;
}
return (int) result;
}
}
Loading editor...