Find X-Sum of All K-Long Subarrays I - 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:

  • Count the occurrences of all elements in the array.
  • Keep only the occurrences of the top x most 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: 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,2,3,1], k = 3, x = 2
Output: [8,5]
💡 Note: For subarray [3,2,3]: frequencies are {3:2, 2:1}. Since x=2, take all elements: 3×2 + 2×1 = 8. For subarray [2,3,1]: frequencies are {2:1, 3:1, 1:1}. Take top 2 by frequency,value: 3×1 + 2×1 = 5.
Example 2 — Less Than X Elements
$ Input: nums = [1,1,2], k = 2, x = 4
Output: [2,3]
💡 Note: For subarray [1,1]: only 1 distinct element < x=4, so sum all: 1+1 = 2. For subarray [1,2]: only 2 distinct elements < x=4, so sum all: 1+2 = 3.
Example 3 — Tiebreaker by Value
$ Input: nums = [2,4,2,4], k = 4, x = 2
Output: [12]
💡 Note: Subarray [2,4,2,4] has frequencies {2:2, 4:2}. Both have same frequency, so tiebreaker by value: take 4 (bigger) and 2. Sum: 4×2 + 2×2 = 12.

Constraints

  • 1 ≤ n ≤ 50
  • 1 ≤ nums[i] ≤ 50
  • 1 ≤ k ≤ n
  • 1 ≤ x ≤ k

Visualization

Tap to expand
X-Sum of All K-Long Subarrays INPUT nums = [3, 2, 3, 1] 3 i=0 2 i=1 3 i=2 1 i=3 k = 3 x = 2 Subarray 1: [3,2,3] 3 2 3 Subarray 2: [2,3,1] 2 3 1 Window size k=3, keep x=2 top elements ALGORITHM STEPS 1 Slide Window Extract k-length subarray 2 Count Frequency Track element occurrences 3 Select Top x By freq, then by value 4 Calculate X-Sum Sum top x elements [3,2,3] Frequency: 3 --> 2 times, 2 --> 1 time Top 2: 3(freq=2), 2(freq=1) X-Sum = 3+3+2 = 8 [2,3,1] Frequency: All elements: 1 time each Top 2 by value: 3, 2 X-Sum = 3+2 = 5 FINAL RESULT Output Array: 8 5 answer[0] answer[1] Breakdown: answer[0] = x-sum([3,2,3]) = 3+3+2 = 8 answer[1] = x-sum([2,3,1]) = 3+2 = 5 Final Answer: [8, 5] OK - All subarrays processed! Key Insight: The X-Sum keeps only the TOP x most frequent elements. When frequencies are equal, LARGER values are prioritized. For [2,3,1] with all freq=1, we pick 3 and 2 (highest values). Use a sliding window approach with frequency map for optimal O(n*k) time complexity. TutorialsPoint - Find X-Sum of All K-Long Subarrays I | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
342 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