Leetcode 2913. Subarrays Distinct Element Sum of Squares I
You are given an array of integers nums
and an integer k
. A subarray is a contiguous non-empty sequence of elements within an array. The distinct element sum of squares of a subarray is the sum of squares of its distinct elements. Return the sum of the distinct element sum of squares for all subarrays of length k
or more in the input array nums
.
For nums = [1, 2, 1, 2, 3]
and k = 2
, we consider all subarrays of length 2 or more:
The total sum would be 5 + 5 + 5 + 14 + 5 = 34.
nums
(n)?nums
guaranteed to be positive integers?k
or more?k
is larger than the length of nums
?nums
contains duplicate elements within subarrays? Are we ensuring that only unique elements’ squares are considered?To solve this problem, we need to consider the following steps:
k
to n
.#include <vector>
#include <unordered_map>
#include <cmath>
#include <unordered_set>
using namespace std;
class Solution {
public:
int subarraysDistinctElementSumOfSquares(vector<int>& nums, int k) {
if (nums.empty() || k > nums.size()) {
return 0;
}
int n = nums.size();
int totalSum = 0;
// Function to calculate the sum of squares of unique elements in the window
auto calculateSumOfSquares = [](unordered_map<int, int>& freqMap) {
int sum = 0;
for (auto& [key, value] : freqMap) {
if (value > 0)
sum += key * key;
}
return sum;
};
// Sliding window to calculate required sum of squares
for (int size = k; size <= n; ++size) {
unordered_map<int, int> freqMap;
int currentSum = 0;
for (int i = 0; i < size; ++i) {
freqMap[nums[i]]++;
}
currentSum = calculateSumOfSquares(freqMap);
totalSum += currentSum;
for (int i = size; i < n; ++i) {
freqMap[nums[i - size]]--;
freqMap[nums[i]]++;
currentSum = calculateSumOfSquares(freqMap);
totalSum += currentSum;
}
}
return totalSum;
}
};
Thus, the overall time complexity would be approximately O(n^2) for larger dimensions of n
and small window sizes starting from k
.
This solution ensures that we efficiently compute the required sum of squares of distinct elements in each valid subarray and sum them up for the result.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?