Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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:
x most frequent elements. If two elements have the same number of occurrences, the element with the bigger value is considered more frequent.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:
[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.[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.[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 <= 501 <= nums[i] <= 501 <= x <= k <= nums.lengthProblem summary: 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].
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Sliding Window
[1,1,2,2,3,4,2,3] 6 2
[3,8,7,8,7,5] 2 2
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3318: Find X-Sum of All K-Long Subarrays I
class Solution {
private TreeSet<int[]> l = new TreeSet<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
private TreeSet<int[]> r = new TreeSet<>(l.comparator());
private Map<Integer, Integer> cnt = new HashMap<>();
private int s;
public int[] findXSum(int[] nums, int k, int x) {
int n = nums.length;
int[] ans = new int[n - k + 1];
for (int i = 0; i < n; ++i) {
int v = nums[i];
remove(v);
cnt.merge(v, 1, Integer::sum);
add(v);
int j = i - k + 1;
if (j < 0) {
continue;
}
while (!r.isEmpty() && l.size() < x) {
var p = r.pollLast();
s += p[0] * p[1];
l.add(p);
}
while (l.size() > x) {
var p = l.pollFirst();
s -= p[0] * p[1];
r.add(p);
}
ans[j] = s;
remove(nums[j]);
cnt.merge(nums[j], -1, Integer::sum);
add(nums[j]);
}
return ans;
}
private void remove(int v) {
if (!cnt.containsKey(v)) {
return;
}
var p = new int[] {cnt.get(v), v};
if (l.contains(p)) {
l.remove(p);
s -= p[0] * p[1];
} else {
r.remove(p);
}
}
private void add(int v) {
if (!cnt.containsKey(v)) {
return;
}
var p = new int[] {cnt.get(v), v};
if (!l.isEmpty() && l.comparator().compare(l.first(), p) < 0) {
l.add(p);
s += p[0] * p[1];
} else {
r.add(p);
}
}
}
// Accepted solution for LeetCode #3318: Find X-Sum of All K-Long Subarrays I
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #3318: Find X-Sum of All K-Long Subarrays I
// class Solution {
// private TreeSet<int[]> l = new TreeSet<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
// private TreeSet<int[]> r = new TreeSet<>(l.comparator());
// private Map<Integer, Integer> cnt = new HashMap<>();
// private int s;
//
// public int[] findXSum(int[] nums, int k, int x) {
// int n = nums.length;
// int[] ans = new int[n - k + 1];
// for (int i = 0; i < n; ++i) {
// int v = nums[i];
// remove(v);
// cnt.merge(v, 1, Integer::sum);
// add(v);
// int j = i - k + 1;
// if (j < 0) {
// continue;
// }
// while (!r.isEmpty() && l.size() < x) {
// var p = r.pollLast();
// s += p[0] * p[1];
// l.add(p);
// }
// while (l.size() > x) {
// var p = l.pollFirst();
// s -= p[0] * p[1];
// r.add(p);
// }
// ans[j] = s;
//
// remove(nums[j]);
// cnt.merge(nums[j], -1, Integer::sum);
// add(nums[j]);
// }
// return ans;
// }
//
// private void remove(int v) {
// if (!cnt.containsKey(v)) {
// return;
// }
// var p = new int[] {cnt.get(v), v};
// if (l.contains(p)) {
// l.remove(p);
// s -= p[0] * p[1];
// } else {
// r.remove(p);
// }
// }
//
// private void add(int v) {
// if (!cnt.containsKey(v)) {
// return;
// }
// var p = new int[] {cnt.get(v), v};
// if (!l.isEmpty() && l.comparator().compare(l.first(), p) < 0) {
// l.add(p);
// s += p[0] * p[1];
// } else {
// r.add(p);
// }
// }
// }
# Accepted solution for LeetCode #3318: Find X-Sum of All K-Long Subarrays I
class Solution:
def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
def add(v: int):
if cnt[v] == 0:
return
p = (cnt[v], v)
if l and p > l[0]:
nonlocal s
s += p[0] * p[1]
l.add(p)
else:
r.add(p)
def remove(v: int):
if cnt[v] == 0:
return
p = (cnt[v], v)
if p in l:
nonlocal s
s -= p[0] * p[1]
l.remove(p)
else:
r.remove(p)
l = SortedList()
r = SortedList()
cnt = Counter()
s = 0
n = len(nums)
ans = [0] * (n - k + 1)
for i, v in enumerate(nums):
remove(v)
cnt[v] += 1
add(v)
j = i - k + 1
if j < 0:
continue
while r and len(l) < x:
p = r.pop()
l.add(p)
s += p[0] * p[1]
while len(l) > x:
p = l.pop(0)
s -= p[0] * p[1]
r.add(p)
ans[j] = s
remove(nums[j])
cnt[nums[j]] -= 1
add(nums[j])
return ans
// Accepted solution for LeetCode #3318: Find X-Sum of All K-Long Subarrays I
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3318: Find X-Sum of All K-Long Subarrays I
// class Solution {
// private TreeSet<int[]> l = new TreeSet<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
// private TreeSet<int[]> r = new TreeSet<>(l.comparator());
// private Map<Integer, Integer> cnt = new HashMap<>();
// private int s;
//
// public int[] findXSum(int[] nums, int k, int x) {
// int n = nums.length;
// int[] ans = new int[n - k + 1];
// for (int i = 0; i < n; ++i) {
// int v = nums[i];
// remove(v);
// cnt.merge(v, 1, Integer::sum);
// add(v);
// int j = i - k + 1;
// if (j < 0) {
// continue;
// }
// while (!r.isEmpty() && l.size() < x) {
// var p = r.pollLast();
// s += p[0] * p[1];
// l.add(p);
// }
// while (l.size() > x) {
// var p = l.pollFirst();
// s -= p[0] * p[1];
// r.add(p);
// }
// ans[j] = s;
//
// remove(nums[j]);
// cnt.merge(nums[j], -1, Integer::sum);
// add(nums[j]);
// }
// return ans;
// }
//
// private void remove(int v) {
// if (!cnt.containsKey(v)) {
// return;
// }
// var p = new int[] {cnt.get(v), v};
// if (l.contains(p)) {
// l.remove(p);
// s -= p[0] * p[1];
// } else {
// r.remove(p);
// }
// }
//
// private void add(int v) {
// if (!cnt.containsKey(v)) {
// return;
// }
// var p = new int[] {cnt.get(v), v};
// if (!l.isEmpty() && l.comparator().compare(l.first(), p) < 0) {
// l.add(p);
// s += p[0] * p[1];
// } else {
// r.add(p);
// }
// }
// }
// Accepted solution for LeetCode #3318: Find X-Sum of All K-Long Subarrays I
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3318: Find X-Sum of All K-Long Subarrays I
// class Solution {
// private TreeSet<int[]> l = new TreeSet<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
// private TreeSet<int[]> r = new TreeSet<>(l.comparator());
// private Map<Integer, Integer> cnt = new HashMap<>();
// private int s;
//
// public int[] findXSum(int[] nums, int k, int x) {
// int n = nums.length;
// int[] ans = new int[n - k + 1];
// for (int i = 0; i < n; ++i) {
// int v = nums[i];
// remove(v);
// cnt.merge(v, 1, Integer::sum);
// add(v);
// int j = i - k + 1;
// if (j < 0) {
// continue;
// }
// while (!r.isEmpty() && l.size() < x) {
// var p = r.pollLast();
// s += p[0] * p[1];
// l.add(p);
// }
// while (l.size() > x) {
// var p = l.pollFirst();
// s -= p[0] * p[1];
// r.add(p);
// }
// ans[j] = s;
//
// remove(nums[j]);
// cnt.merge(nums[j], -1, Integer::sum);
// add(nums[j]);
// }
// return ans;
// }
//
// private void remove(int v) {
// if (!cnt.containsKey(v)) {
// return;
// }
// var p = new int[] {cnt.get(v), v};
// if (l.contains(p)) {
// l.remove(p);
// s -= p[0] * p[1];
// } else {
// r.remove(p);
// }
// }
//
// private void add(int v) {
// if (!cnt.containsKey(v)) {
// return;
// }
// var p = new int[] {cnt.get(v), v};
// if (!l.isEmpty() && l.comparator().compare(l.first(), p) < 0) {
// l.add(p);
// s += p[0] * p[1];
// } else {
// r.add(p);
// }
// }
// }
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.