Find X-Sum of All K-Long Subarrays II - Problem

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:

  1. Count the occurrences of all elements in the array.
  2. Keep only the occurrences of the top x most frequent elements.
  3. If two elements have the same number of occurrences, the element with the bigger value is considered more frequent.
  4. 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].

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,8,7,8,7,5], k = 2, x = 2
Output: [11,15,15,15,12]
💡 Note: For subarray [3,8]: frequencies are 3→1, 8→1. Top 2 by frequency then value: 8,3. Sum = 8×1 + 3×1 = 11. For [8,7]: 8→1, 7→1. Top 2: 8,7. Sum = 8×1 + 7×1 = 15.
Example 2 — Single Top Element
$ Input: nums = [1,1,1,2,2,2], k = 4, x = 1
Output: [2,4,4]
💡 Note: For [1,1,1,2]: 1→3, 2→1. Top 1: element 1 with freq 3. Sum = 1×3 = 3. Wait, let me recalculate: 1 appears 3 times, 2 appears 1 time. Top 1 most frequent: 1 (freq=3). Sum = 1×3 = 3.
Example 3 — All Elements
$ Input: nums = [1,2], k = 2, x = 3
Output: [3]
💡 Note: Subarray [1,2] has only 2 distinct elements, which is less than x=3, so x-sum is just the sum of the array: 1 + 2 = 3.

Constraints

  • 1 ≤ n ≤ 5 × 104
  • 1 ≤ nums[i] ≤ 50
  • 1 ≤ k ≤ min(n, 50)
  • 1 ≤ x ≤ k

Visualization

Tap to expand
X-Sum of All K-Long Subarrays II INPUT nums array: 3 8 7 8 7 5 0 1 2 3 4 5 k = 2 x = 2 k = window size x = top frequent count Sliding Windows: [3,8] [8,7] [7,8] [8,7] [7,5] ALGORITHM STEPS 1 Slide Window Move k-size window across array 2 Count Frequencies Track element occurrences 3 Select Top X Keep x most frequent (max val tie) 4 Calculate Sum Sum selected elements Example: Window [3,8] Freq: 3->1, 8->1 Top 2: 8(freq=1), 3(freq=1) Tie: pick larger value first X-Sum = 3 + 8 = 11 FINAL RESULT Output Array: 11 15 15 15 12 Breakdown: [3,8] --> 3+8 = 11 [8,7] --> 8+7 = 15 [7,8] --> 7+8 = 15 [8,7] --> 8+7 = 15 [7,5] --> 7+5 = 12 OK - Complete 5 x-sums found Key Insight: Use two balanced BSTs (or sorted sets) to efficiently maintain top-x elements as the window slides. One set keeps the top x elements by (frequency, value), the other holds remaining elements. This achieves O(n log k) time complexity vs O(n*k log k) with naive approach. TutorialsPoint - Find X-Sum of All K-Long Subarrays II | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8
15.6K Views
Medium Frequency
~25 min Avg. Time
428 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen