LeetCode 3318: Find X-Sum of All K-Long Subarrays I
Problem Description
Explanation
This problem involves calculating the x-sum of all k-long subarrays of an array nums
. The x-sum is calculated by keeping only the occurrences of the top x most frequent elements in the subarray. If the subarray has less than x distinct elements, the x-sum is the sum of the subarray.
To solve this problem, we can use a sliding window approach. We will maintain a HashMap to keep track of the frequency of elements in the current window. At each step, we update the frequency count, remove elements that are no longer in the window, and calculate the x-sum based on the top x most frequent elements.
The time complexity of this approach is O(n) where n is the length of the input array. The space complexity is O(n) to store the frequency of elements in the HashMap.
Solutions
class Solution {
public int[] findXSumOfAllKLongSubarrays(int[] nums, int k, int x) {
int n = nums.length;
Map<Integer, Integer> freqMap = new HashMap<>();
List<Integer> xSumList = new ArrayList<>();
int[] answer = new int[n - k + 1];
for (int i = 0; i < n; i++) {
freqMap.put(nums[i], freqMap.getOrDefault(nums[i], 0) + 1);
if (i >= k - 1) {
Set<Map.Entry<Integer, Integer>> entrySet = freqMap.entrySet();
List<Map.Entry<Integer, Integer>> sortedList = new ArrayList<>(entrySet);
sortedList.sort((a, b) -> a.getValue() == b.getValue() ? Integer.compare(b.getKey(), a.getKey()) : Integer.compare(b.getValue(), a.getValue()));
int sum = 0;
for (int j = 0; j < x && j < sortedList.size(); j++) {
sum += sortedList.get(j).getKey() * sortedList.get(j).getValue();
}
xSumList.add(sum);
int leftElement = nums[i - k + 1];
if (freqMap.get(leftElement) == 1) {
freqMap.remove(leftElement);
} else {
freqMap.put(leftElement, freqMap.get(leftElement) - 1);
}
}
}
for (int i = 0; i < xSumList.size(); i++) {
answer[i] = xSumList.get(i);
}
return answer;
}
}
Loading editor...