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:

  1. Initialize variables result to store the final answer and MOD as 10^9 + 7.
  2. Initialize an empty hashmap count to store the frequency of elements in the current window.
  3. Initialize left and right pointers for the sliding window technique.
  4. Iterate over the array using the right pointer and update the count hashmap.
  5. For each element added, update the result by adding the square of the current distinct count.
  6. Move the left pointer while incrementing it and update the count hashmap accordingly.
  7. Repeat steps 4-6 until right reaches the end of the array.
  8. Finally, return the result modulo MOD.

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...