Find X-Sum of All K-Long Subarrays II Problem
Description
LeetCode Problem 3321.
You are given an array nums of n integers and two integers k and x.
The x-sum of an array is calculated by the following procedure:
- Count the occurrences of all elements in the array.
- Keep only the occurrences of the top
xmost frequent elements. If two elements have the same number of occurrences, the element with the bigger value is considered more frequent. - Calculate the sum of the resulting array.
Note that if an array has less than x distinct elements, its x-sum is the sum of the array.
Return an integer array answer of length n - k + 1 where answer[i] is the x-sum of the subarray nums[i..i + k - 1].
Example 1:
Input: nums = [1,1,2,2,3,4,2,3], k = 6, x = 2
Output: [6,10,12]
Explanation:
- For subarray [1, 1, 2, 2, 3, 4], only elements 1 and 2 will be kept in the resulting array. Hence, answer[0] = 1 + 1 + 2 + 2.
- For subarray [1, 2, 2, 3, 4, 2], only elements 2 and 4 will be kept in the resulting array. Hence, answer[1] = 2 + 2 + 2 + 4. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.
- For subarray [2, 2, 3, 4, 2, 3], only elements 2 and 3 are kept in the resulting array. Hence, answer[2] = 2 + 2 + 2 + 3 + 3.
Example 2:
Input: nums = [3,8,7,8,7,5], k = 2, x = 2
Output: [11,15,15,15,12]
Explanation:
Since k == x, answer[i] is equal to the sum of the subarray nums[i..i + k - 1].
Constraints:
nums.length == n1 <= n <= 10^51 <= nums[i] <= 10^91 <= x <= k <= nums.length
Solution
Approach: Hash Table + Ordered Set
Slide a window of length k over the array. Keep a hash table cnt with the frequency of every value in the window, and rank the values by the pair (frequency, value), larger pair meaning more important. Split the distinct values into two ordered sets: l holds the x best pairs (the ones that count towards the x-sum) and r holds the rest. A running total s is the sum of frequency * value over l.
When a value is added to or removed from the window, take its old pair out of whichever set holds it, update cnt, and insert the new pair: into l if it beats the smallest pair of l, otherwise into r. After the first k elements and after each slide, rebalance: while l has fewer than x pairs and r is not empty, move the largest pair of r into l; while l has more than x, move its smallest pair to r. Then s is the x-sum of the current window.
The reference code stores each pair as a single number frequency * 2^30 + value in a sorted array so that no tree library is needed; Java and C++ use their built-in ordered sets.
Complexity: O(n log k) time with balanced ordered sets and O(n) space, where n is the length of nums.
from bisect import bisect_left, insort
class Solution:
def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
# (count, value) pairs are packed into one integer: count * 2^30 + value
B = 1 << 30
def add(v: int):
nonlocal s
if cnt.get(v, 0) == 0:
return
p = cnt[v] * B + v
if l and p > l[0]:
s += cnt[v] * v
insort(l, p)
else:
insort(r, p)
def remove(v: int):
nonlocal s
if cnt.get(v, 0) == 0:
return
p = cnt[v] * B + v
i = bisect_left(l, p)
if i < len(l) and l[i] == p:
s -= cnt[v] * v
l.pop(i)
else:
r.pop(bisect_left(r, p))
l = []
r = []
cnt = {}
s = 0
n = len(nums)
ans = [0] * (n - k + 1)
for i, v in enumerate(nums):
remove(v)
cnt[v] = cnt.get(v, 0) + 1
add(v)
j = i - k + 1
if j < 0:
continue
while r and len(l) < x:
p = r.pop()
l.insert(0, p)
s += (p // B) * (p % B)
while len(l) > x:
p = l.pop(0)
s -= (p // B) * (p % B)
insort(r, p)
ans[j] = s
remove(nums[j])
cnt[nums[j]] -= 1
add(nums[j])
return ans