← Questions
K largest subset sums
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Jan 2026. It tests heaps and sorting.
You get n items with non-negative integer weights and an integer k. Every subset of the items has a sum (the empty subset sums to 0). Return the k largest subset sums in decreasing order. Subsets are counted by the items they contain, so two different subsets with the same sum both appear.
Interface
Unless you agree on a different interface with the interviewer, assume:
k_largest_subset_sums(weights: list[int], k: int) -> list[int]
Example
weights = [3, 1, 2], k = 4 -> [6, 5, 4, 3]
weights = [3, 1, 2], k = 5 -> [6, 5, 4, 3, 3] # {3} and {1, 2} both sum to 3
weights = [5, 5], k = 3 -> [10, 5, 5]
Constraints
-
1 <= n <= 10^5;0 <= weights[i] <= 10^9. -
kis at most2^nand small enough that the answer fits in memory (think thousands), whilenis far too large to enumerate subsets.
Clarifying questions
- Can weights be negative?
- Do equal sums from different subsets each count?
- How large can
kbe compared withn?
What a strong answer covers
- Why brute force (2^n subsets) is impossible.
- The reframing: the largest sum is the total; the next ones are the total minus the smallest subset sums, so find the
ksmallest subset sums. - Generating smallest subset sums in order with a min-heap over sorted weights: from a state
(sum, i)whose largest used index isi, push(sum + w[i+1], i+1)(add the next item) and(sum - w[i] + w[i+1], i+1)(swap the last item for the next). Each subset is produced exactly once. - O(n log n + k log k) time, O(k) heap space.
- Checking against brute force on small random inputs.
Follow-ups
- Weights may be negative: the largest sum is the sum of the positives, and every weight's absolute value becomes a cost to subtract.
- Return the
k-th largest only, for a very largek. - Return the subsets themselves, not only the sums.
Where it's asked
- Google · First round: coding · Last asked Jan 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
