Skip to main content

Find X-Sum of All K-Long Subarrays I - Solution & Explanation

EasyArrayHash TableSliding WindowHeap (Priority Queue)22 min readAsked at: Amazon, Microsoft, Meta +2
Practice this problem

Problem Statement

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 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].

 

Example 1:

Input: nums = [1,1,2,2,3,4,2,3], k = 6, x = 2

Output: [6,10,12]

Explanation:

  • For subarray [1, 1, 2, 2, 3, 4], only elements 1 and 2 will be kept in the resulting array. Hence, answer[0] = 1 + 1 + 2 + 2.
  • For subarray [1, 2, 2, 3, 4, 2], only elements 2 and 4 will be kept in the resulting array. Hence, answer[1] = 2 + 2 + 2 + 4. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.
  • For subarray [2, 2, 3, 4, 2, 3], only elements 2 and 3 are kept in the resulting array. Hence, 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, answer[i] is equal to the sum of the subarray nums[i..i + k - 1].

 

Constraints:

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

Approach Overview

Problem Overview: You receive an array nums and integers k and x. For every contiguous subarray of length k, compute the x-sum. The x-sum is formed by selecting the x numbers with the highest frequency in that window (tie broken by larger value) and summing frequency * value for those numbers. The result is an array containing the x-sum for each window.

Approach 1: Brute Force with Sorting (Time: O(n * k log k), Space: O(k))

Process each window independently. For every starting index, iterate through the next k elements and build a frequency map using a hash table. Convert the map entries into a list of (value, frequency) pairs. Sort this list by frequency descending, and if frequencies match, by value descending. Take the first x elements and add frequency * value to compute the window’s x-sum.

This approach is straightforward and mirrors the definition of the problem. The drawback is repeated work: each window rebuilds the frequency map and performs sorting again. Sorting up to k unique elements costs O(k log k), and this happens for roughly n windows. Still, this solution is easy to implement and works well when k is small.

Approach 2: Optimized Sliding Window with Heap (Time: O(n log k), Space: O(k))

Instead of recomputing everything for each window, maintain a running frequency map while sliding the window across the array. Add the new element entering the window and decrement the frequency of the element leaving it. This technique uses the classic sliding window pattern to avoid rebuilding counts.

To efficiently determine the top x elements by frequency and value, maintain a priority queue (max heap) containing pairs representing the current frequency and value. Each time the window changes, push updated entries into the heap. When computing the x-sum, repeatedly extract the best candidates from the heap while discarding outdated entries whose stored frequency no longer matches the value in the frequency map.

This method reduces the need to sort the entire frequency list every time. Heap operations cost O(log k), and each element update happens only when the window moves. The combination of a hash table for counting and a heap (priority queue) for ranking elements makes the process efficient for larger inputs.

Recommended for interviews: Start by explaining the brute force approach to demonstrate understanding of the x-sum definition and ordering rule. Then transition to the optimized sliding window solution. Interviewers expect candidates to recognize that overlapping windows share most of their elements, so maintaining frequencies incrementally and using a heap to retrieve the top x contributors shows strong algorithmic thinking.

Approach 1: Brute Force with Sorting

This approach involves iterating over each possible k-length subarray, counting the occurrences of elements, and then selecting the top x elements by sorting the count and element value.

The sorted elements are then summed to determine the x-sum for each subarray. This method is simple but not optimal for larger input sizes.

The solution iterates over each k-length subarray, calculates the frequency of each element in a frequency array, then sorts this array to find the top x frequent elements using their values to break ties. It then calculates the sum of these elements and stores it in the result array.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O((n-k+1)*51^2), where 51 is the possible range of elements. Space Complexity: O(51) for storing counts.

Try this approach in the editor →

Approach 2: Optimized Sliding Window

This approach employs a sliding window to maintain the frequency count between subarrays. This allows the reuse of previously calculated frequencies, significantly reducing redundant work by removing the frequency of the outgoing element while adding the frequency of the new incoming element.

This C implementation uses a sliding window on the k-length subarray by adjusting frequency counts as the window slides. This reduces computational overhead as the program recalculates less frequently than recalculating frequency from scratch for each subarray.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n*51^2), where n is the number of elements. Space Complexity: O(51).

Try this approach in the editor →

Approach 3: Hash Table + Ordered Set

We use a hash table cnt to count the occurrences of each element in the window, an ordered set l to store the x elements with the highest occurrences in the window, and another ordered set r to store the remaining elements.

We maintain a variable s to represent the sum of the elements in l. Initially, we add the first k elements to the window, update the ordered sets l and r, and calculate the value of s. If the size of l is less than x and r is not empty, we repeatedly move the largest element from r to l until the size of l equals x, updating the value of s in the process. If the size of l is greater than x, we repeatedly move the smallest element from l to r until the size of l equals x, updating the value of s in the process. At this point, we can calculate the current window's x-sum and add it to the answer array. Then we remove the left boundary element of the window, update cnt, and update the ordered sets l and r, as well as the value of s. Continue traversing the array until the traversal is complete.

The time complexity is O(n times log k), and the space complexity is O(n). Here, n is the length of the array nums.

Similar problems:

Code

Python

Java

C++

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Brute Force with Sorting

Time Complexity: O((n-k+1)*51^2), where 51 is the possible range of elements. Space Complexity: O(51) for storing counts.

Optimized Sliding Window

Time Complexity: O(n*51^2), where n is the number of elements. Space Complexity: O(51).

Hash Table + Ordered Set

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force with SortingO(n * k log k)O(k)Simple implementation or when k is small and performance constraints are loose
Sliding Window with HeapO(n log k)O(k)Large arrays where recomputing frequencies and sorting every window is too slow

Video Solution

Find X-Sum of All K-Long Subarrays I | Revise DSA Fundamentals | Dry Run | Leetcode 3318 | MIKcodestorywithMIK7,656 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Find X-Sum of All K-Long Subarrays I easy or hard?
The problem is rated Easy because the brute force solution is straightforward: count frequencies and sort them for each window. The challenge increases slightly when optimizing with a sliding window and heap, which introduces common interview data structures.
Find X-Sum of All K-Long Subarrays I Python/Java solution
In Python or Java, implement a sliding window with a dictionary or HashMap to track frequencies. Use a priority queue to keep elements ordered by frequency and value. For each window, extract the top x valid entries and compute the sum of frequency multiplied by value.
How to solve Find X-Sum of All K-Long Subarrays I in O(n)?
A strict O(n) solution is difficult because each window must determine the top x elements by frequency and value. The practical optimized solution achieves O(n log k) using a sliding window to update counts and a heap to retrieve the highest-ranked elements efficiently.
What is the best approach for Find X-Sum of All K-Long Subarrays I?
The most efficient approach uses a sliding window combined with a hash table and a max heap. The sliding window maintains element frequencies as the window moves, while the heap helps retrieve the top x elements by frequency and value. This reduces repeated sorting and runs in O(n log k) time with O(k) extra space.
Is Find X-Sum of All K-Long Subarrays I asked at Google/Amazon/Meta?
Problems involving sliding window frequency tracking and priority queues commonly appear in interviews at companies like Amazon, Google, and Meta. While this exact problem may not always appear, the underlying techniques—frequency maps, window updates, and heap ranking—are standard interview patterns.
What data structure is used in Find X-Sum of All K-Long Subarrays I?
The solution typically uses a hash table to store frequencies of elements in the current window and a max heap (priority queue) to rank elements by frequency and value. The sliding window technique updates these structures efficiently as the window moves.
What is the time complexity of Find X-Sum of All K-Long Subarrays I?
The brute force method takes O(n * k log k) time because every window rebuilds a frequency map and sorts the elements. An optimized sliding window with a heap reduces the complexity to O(n log k) by updating counts incrementally and using heap operations instead of full sorting.

Ready to solve this problem?

Practice Find X-Sum of All K-Long Subarrays I with our built-in code editor and test cases.

Practice on FleetCode