15% off all plans & roadmaps Use code

See plans

Find X-Sum of All K-Long Subarrays I

Updated

TL;DR: Each window of length k needs the sum of its top x most frequent values, with ties going to the bigger value. Slide the window one step at a time, update the counts in O(1), and select the top x from those counts.

Problem

You are given an array nums of n integers and two integers k and x.

The x-sum of an array is computed with this procedure:

  • Count how many times each element occurs in the array.
  • Keep only the occurrences of the top x most frequent elements. If two elements occur the same number of times, the element with the bigger value counts as more frequent.
  • Add up the values that remain. That total is the x-sum.

If an array has fewer than x distinct elements, its x-sum is the sum of the whole 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 the subarray [1, 1, 2, 2, 3, 4], only 1 and 2 are kept. So answer[0] = 1 + 1 + 2 + 2.
- For the subarray [1, 2, 2, 3, 4, 2], only 2 and 4 are kept. So answer[1] = 2 + 2 + 2 + 4. The value 4 wins the tie against 3 and 1 because it is bigger.
- For the subarray [2, 2, 3, 4, 2, 3], only 2 and 3 are kept. So 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, every window keeps all of its elements. So answer[i] is the plain sum of nums[i..i + k - 1].

Constraints

  • 1 <= n == nums.length <= 50
  • 1 <= nums[i] <= 50
  • 1 <= x <= k <= nums.length

Constraints that matter

  • n is at most 50 and values are at most 50, so at most 50 distinct values can ever appear. Any per-window selection works on a list that never grows past 50 entries.
  • k can be as large as n, so the brute force can afford to recount each window. Total counting work is at most n * k, which is about 2500 steps here, but the same method would not scale to larger limits.
  • x can be as large as k, so the selection must stop early when the list of distinct values runs out. Reading past the end of that list is a bug, not a special case.
  • Sums never exceed 50 * 50 = 2500, so a plain int works in every language. No big-number handling is needed.

View on LeetCode

Hints

Hint 1

This problem asks about every window of one fixed length k.

Hint 2

This is the naive solution.

Solution

Intuition

This problem asks about every window of one fixed length k. That is the fixed-size sliding window pattern, and it has one key property. Two neighboring windows share k - 1 elements. The only change is that one element leaves on the left and one enters on the right.

Picture a row of numbered mailboxes, one per value, each holding a tally slip that counts the letters inside. The mailboxes are the count array, and each slide drops one letter out of the back box and loads one into the front box, so only two slips change.

So you do not need to recount a window from scratch. Keep one count per value for the current window. When the window moves, decrement the count of the outgoing value and increment the count of the incoming value. Both updates cost O(1), and the counts always describe the current window.

The remaining work is selection, and the tie rule fits a sort key. Turn each present value into a (count, value) pair. Sort the pairs in descending order, and the first x pairs are the top x under the problem's ranking. Their products add up to the x-sum.

The selection step stays cheap here because the values run from 1 to 50. The sort never handles more than 50 pairs, so its cost is a fixed bound per window.

Watch the pattern animation

Worked example

Input: nums = [5, 5, 5, 5, 5], k = 3, x = 1
Output: [15, 15, 15]
Explanation: Every window of length 3 holds three copies of 5. With x = 1, only the most frequent value survives, and that is 5 with count 3. Each window therefore sums to 3 * 5 = 15. The trace below shows the counts changing while the answer stays the same.

Approach 1: Brute force

This is the naive solution. For each window, copy its k elements, count them with a hash map, sort the distinct values by the tie rule, and add the top x products. Nothing carries over between windows, so each window pays the full counting and sorting cost again. The method is correct for every input, which makes it a safe baseline to explain first.

Steps

  1. Let the answer have n - k + 1 slots. For each start index i from 0 to n - k, take the slice nums[i..i + k - 1].
  2. Count how many times each value appears in that slice with a hash map.
  3. Turn each map entry into a (count, value) pair.
  4. Sort the pairs in descending order. Comparing the count first and the value second applies the tie rule.
  5. Add count * value for the first x pairs. If there are fewer than x pairs, add all of them.
  6. Store the sum at answer[i] and move to the next window.

Dry run

Use nums = [5, 5, 5, 5, 5], k = 3, x = 1. There are 5 - 3 + 1 = 3 windows.

  • Window i = 0 is [5, 5, 5]. The map is {5: 3}. The pairs are [(3, 5)]. The first pair gives 3 * 5 = 15. answer = [15].
  • Window i = 1 is [5, 5, 5]. The map is {5: 3}. The pairs are [(3, 5)]. The sum is 15. answer = [15, 15].
  • Window i = 2 is [5, 5, 5]. The map is {5: 3}. The pairs are [(3, 5)]. The sum is 15. answer = [15, 15, 15].

The trace ends on [15, 15, 15], which matches the expected output.

Complexity

TimeO(n * k log k)
SpaceO(k)

Let n be the array length and k the window length. There are n - k + 1 windows, and each one counts its k elements, which costs O(k). The distinct values are at most k, so sorting their pairs costs O(k log k), and n - k + 1 windows give O(n * k log k). The map and the pair list hold at most k entries each, so the extra space is O(k).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
        n = len(nums)
        answer = []
        for i in range(n - k + 1):
            # Count the values in this window from scratch
            freq = {}
            for v in nums[i:i + k]:
                freq[v] = freq.get(v, 0) + 1
            # Sort by (count, value) descending, which applies the tie rule
            pairs = sorted(((c, v) for v, c in freq.items()), reverse=True)
            total = 0
            for c, v in pairs[:x]:
                total += c * v
            answer.append(total)
        return answer

The Fixed Size (Subarray Calculation) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Fixed Size (Subarray Calculation)

Part of Sliding Window

Approach 2: Sliding window counts, then top x by sortOptimalFixed Size (Subarray Calculation)

What is slow: the brute force recounts the k - 1 shared elements from scratch on every window. The insight that fixes it: moving the window changes exactly two counts, one decrement and one increment. Keep one count per value and update it on each slide. The sort still runs per window, but values are at most 50, so it handles a fixed-size list, which keeps the total linear in n.

Why it is correct. The count array always matches the current window, because each slide removes exactly the outgoing element and adds exactly the incoming one. Sorting all present values by (count, value) descending puts the true top x first, so the products summed are exactly the ones required.

Steps

  1. Create a count array of length 51, indexed by value. Values run from 1 to 50.
  2. Add the first k elements to the count array.
  3. Compute the window's x-sum. Collect a (count, value) pair for each value with a count above 0, sort the pairs in descending order, and add the first x products.
  4. Store that sum as answer[0].
  5. For each start index i from k to n - 1, decrement count[nums[i - k]] and increment count[nums[i]].
  6. Recompute the x-sum and store it at answer[i - k + 1]. Return answer after the last window.

Dry run

Use nums = [5, 5, 5, 5, 5], k = 3, x = 1. The table tracks the count of value 5, the sorted pairs, and the answer so far.

StepWindowActioncount[5]Sorted pairsTop x sum (x = 1)answer
Initindices 0 to 2add nums[0], nums[1], nums[2]3(3, 5)3 * 5 = 15[15]
i = 3indices 1 to 3remove nums[0] (5), add nums[3] (5)2, then 3(3, 5)15[15, 15]
i = 4indices 2 to 4remove nums[1] (5), add nums[4] (5)2, then 3(3, 5)15[15, 15, 15]

The final answer is [15, 15, 15]. The count goes down and back up on each slide, which shows that the decrement and the increment both matter.

Complexity

TimeO(n)
SpaceO(1) extra, plus the output array

Let n be the array length. The initial fill costs k steps, and each of the n - k slides does two O(1) count updates, so all count maintenance is O(n). Each window sorts at most 50 pairs, a fixed amount, so n - k + 1 windows cost O(n) overall. The count array has 51 slots and the pair list has at most 50 entries, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
        n = len(nums)
        # Values are 1 to 50, so index by value
        count = [0] * 51
        for i in range(k):
            count[nums[i]] += 1

        def x_sum() -> int:
            # Pairs (count, value) for values present in the window
            present = [(count[v], v) for v in range(1, 51) if count[v] > 0]
            present.sort(reverse=True)
            return sum(c * v for c, v in present[:x])

        answer = [x_sum()]
        for i in range(k, n):
            count[nums[i - k]] -= 1  # the value leaving the window
            count[nums[i]] += 1      # the value entering the window
            answer.append(x_sum())
        return answer

Common mistakes

  • The slide step skips count[nums[i - k]]--. The count keeps a value that already left the window, so every later sum comes out too large. Decrement the outgoing value on every slide.
  • The sort uses ascending order, or it sorts on count alone. Ascending picks the least frequent values, and count-only sorting ignores the tie rule. Sort descending on the pair (count, value).
  • The selection reads present[x - 1] without a length check. When the window has fewer than x distinct values, that read runs past the end. Stop the loop at min(x, len(present)) instead.
  • The count array is sized [0] * 50 while count[nums[i]] is used directly. A value of 50 needs index 50, so the array must have 51 slots when values run from 1 to 50.
  • The brute force loop runs i up to n instead of n - k. That either overruns the array or produces extra answers. Use range(n - k + 1) so the output has exactly n - k + 1 entries.
  • The code sorts by value first and count second. That picks big values even when a smaller value is more frequent. Frequency is the primary key, and value only breaks ties.

Edge cases

  • k = 1 and x = 1: every window holds one element, so answer equals nums. For nums = [4, 9], the output is [4, 9].
  • x = k: every element is kept, so answer[i] is the plain window sum. Example 2 is this case with k = 2.
  • Fewer distinct values than x: nums = [7, 7, 7], k = 3, x = 2. Only one value exists, so the x-sum is 7 * 3 = 21.
  • Count tie with a value tie-break: nums = [1, 4], k = 2, x = 1. Both values appear once, and 4 is bigger, so the x-sum is 4.
  • Maximum size: n = 50 and k = 50. There is exactly one window, so the output has length 1.
  • Single window with repeated values: nums = [50, 50, 1, 1, 1], k = 5, x = 1. The value 1 has count 3 and wins on frequency, so the x-sum is 3.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Find X-Sum of All K-Long Subarrays I, with how to answer them.

Unlock the follow-ups

Find X-Sum of All K-Long Subarrays I FAQ

What is the time complexity of Find X-Sum of All K-Long Subarrays I?

The sliding window version runs in O(n) for this problem, because values are at most 50 and each window sorts a fixed-size list. The brute force version runs in O(n * k log k). Both bounds come from counting the work per window and per slide.

Why use a sliding window for Find X-Sum of All K-Long Subarrays I?

Consecutive windows differ by one element entering and one element leaving. Updating two counts costs O(1), so you avoid recounting k elements for every window. The fixed-size window pattern turns each step into a constant update.

Can Find X-Sum of All K-Long Subarrays I be solved in O(1) extra space?

Yes. The count array has 51 slots and the pair list has at most 50 entries, so the working space is constant. Only the output array grows with n - k + 1, and that array is the result.

Why does the tie rule need the value as the second sort key?

Two values with the same count must be ordered by value, with the bigger value first. Sorting the pairs (count, value) in descending order applies both rules in one comparison. Sorting on count alone leaves ties in an arbitrary order.

What happens when x is larger than the number of distinct values?

The selection loop stops at the shorter of x and the number of distinct values. So the sum covers every present value, which equals the sum of the whole window. The code stays correct without a special case.

Asked at

See which companies ask this — Pro

Practise it