← Questions

K largest subset sums

0
GoogleCodingLast asked Jan 2026

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.
  • k is at most 2^n and small enough that the answer fits in memory (think thousands), while n is far too large to enumerate subsets.

Clarifying questions

  • Can weights be negative?
  • Do equal sums from different subsets each count?
  • How large can k be compared with n?

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 k smallest subset sums.
  • Generating smallest subset sums in order with a min-heap over sorted weights: from a state (sum, i) whose largest used index is i, 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 large k.
  • 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

heaps · sorting

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