Find X-Sum of All K-Long Subarrays II - Problem
You're given an array nums of n integers and two integers k and x. Your task is to find the x-sum for every subarray of length k.
The x-sum of an array is calculated using this procedure:
- Count occurrences: Count how many times each element appears in the array
- Select top x frequent: Keep only the x most frequent elements. If two elements have the same frequency, the larger value is considered more frequent
- Calculate sum: Sum all occurrences of these selected elements
Special case: If the array has fewer than x distinct elements, the x-sum is simply the sum of all elements.
Goal: Return an array where answer[i] is the x-sum of the subarray nums[i..i+k-1].
Example: For array [3,8,7,8,7,5] with k=2, x=2, the subarray [8,7] has frequencies: 8β1, 7β1. Since both have same frequency, we pick both (8 > 7), so x-sum = 8 + 7 = 15.
Input & Output
example_1.py β Basic Case
$
Input:
nums = [3,8,7,8,7,5], k = 2, x = 2
βΊ
Output:
[11, 15, 15, 15, 12]
π‘ Note:
For k=2, x=2: [3,8]β{3:1,8:1}β8+3=11; [8,7]β{8:1,7:1}β8+7=15; [7,8]β{7:1,8:1}β8+7=15; [8,7]β{8:1,7:1}β8+7=15; [7,5]β{7:1,5:1}β7+5=12
example_2.py β Repeated Elements
$
Input:
nums = [1,1,2,2,3,4,2,3], k = 6, x = 2
βΊ
Output:
[6, 10, 12]
π‘ Note:
For k=6, x=2: [1,1,2,2,3,4]β{2:2,1:2,3:1,4:1}β2Γ2+1Γ2=6 (ties broken by value); [1,2,2,3,4,2]β{2:3,others:1}β2Γ3+4Γ1=10; [2,2,3,4,2,3]β{2:3,3:2}β2Γ3+3Γ2=12
example_3.py β Edge Case
$
Input:
nums = [3,8,7,8,7,5], k = 2, x = 1
βΊ
Output:
[8, 8, 8, 8, 7]
π‘ Note:
For x=1, only pick most frequent element: [3,8]β8; [8,7]β8; [7,8]β8; [8,7]β8; [7,5]β7 (both have freq 1, pick larger)
Constraints
- 1 β€ n β€ 5 Γ 104
- 1 β€ nums[i] β€ 109
- 1 β€ k β€ n
- 1 β€ x β€ k
- n is the length of the array nums
Visualization
Tap to expand
Understanding the Visualization
1
Count Frequencies
Count how many times each element appears in the current window
2
Rank Elements
Sort elements by frequency (descending), then by value (descending) for ties
3
Select Top-X
Pick the first min(x, distinct_elements) from the ranked list
4
Calculate Sum
Multiply each selected element by its frequency and sum the results
Key Takeaway
π― Key Insight: Efficiently track frequencies in sliding windows and use proper tie-breaking (higher value wins) to determine the top-x elements for each subarray.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code