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
Find X-Sum of All K-Long Subarrays: nums=[3,8,7,8,7,5], k=2, x=2Input Array:387875Subarray [3,8]Freq: 3→1, 8→1Top-2: 8,3 → Sum=11Process each k-length subarray:1. Count element frequencies2. Sort by frequency (desc), then value (desc)3. Sum top-x elements × their frequenciesOutput: [11, 15, 15, 15, 12]1115151512
Understanding the Visualization
1
Input
Array [3,8,7,8,7,5] with k=2, x=2
2
Process
For each k-length subarray, find top-x most frequent elements
3
Output
Array of x-sums: [11,15,15,15,12]
Key Takeaway
🎯 Key Insight: For each subarray, efficiently find the top-x most frequent elements using frequency counting and sorting/heaps.
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