Leetcode 2913. Subarrays Distinct Element Sum of Squares I
Given an array nums
of integers, the task is to find the sum of the squares of the distinct elements in each subarray of nums
.
Given the problem statement, we can approach it with the following steps:
HashSet
to keep track of distinct elements in the subarray.HashSet
.import java.util.HashSet;
public class Solution {
public long subarraySumOfSquares(int[] nums) {
long totalSum = 0;
// Iterate over all possible subarray starting points
for (int start = 0; start < nums.length; start++) {
HashSet<Integer> distinctElements = new HashSet<>();
// Iterate over all possible subarray ending points
for (int end = start; end < nums.length; end++) {
distinctElements.add(nums[end]); // Add current element to the set
totalSum += sumOfSquares(distinctElements); // Calculate sum of squares
}
}
return totalSum;
}
// Helper method to calculate sum of squares of all elements in the set
private long sumOfSquares(HashSet<Integer> set) {
long sum = 0;
for (int num : set) {
sum += (long) num * num;
}
return sum;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 3};
System.out.println("Total Sum of Squares: " + solution.subarraySumOfSquares(nums));
}
}
O(n)
times where n
is the length of the array.O(n)
times.sumOfSquares
method) is approximately O(1)
for each call, but calculating sum of squares would be O(k)
where k
is the number of distinct elements.Thus, the overall complexity is approximately O(n^3)
in the worst case under the assumption that calculating sum of squares O(n)
times for each subarray. This approach may face performance issues for large input sizes, and we might need to look into optimization strategies such as sliding window techniques or dynamic programming for larger constraints.
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?