Return top-k subset sums in descending order
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in combinatorial reasoning, algorithmic optimization for large search spaces, and efficient extraction of top-k values within the coding & algorithms domain.
Constraints
- 1 <= len(w) <= 2 * 10^5
- 0 <= w[i] <= 10^9
- 1 <= k <= min(2^len(w), 2 * 10^5)
- Use 64-bit integers for subset sums in languages with fixed-width integer types
Examples
Input: ([3, 2, 1], 4)
Expected Output: [6, 5, 4, 3]
Explanation: All subset sums are 0, 1, 2, 3, 3, 4, 5, 6. The top 4 in descending order are [6, 5, 4, 3].
Input: ([5], 2)
Expected Output: [5, 0]
Explanation: The only subsets are {} with sum 0 and {5} with sum 5.
Input: ([0, 2, 2], 6)
Expected Output: [4, 4, 2, 2, 2, 2]
Explanation: Different subsets can have the same sum. The 8 subset sums are 0, 0, 2, 2, 2, 2, 4, 4, so the top 6 are [4, 4, 2, 2, 2, 2].
Input: ([4, 1, 1], 8)
Expected Output: [6, 5, 5, 4, 2, 1, 1, 0]
Explanation: This requests all 2^3 subset sums. In descending order they are [6, 5, 5, 4, 2, 1, 1, 0].
Input: ([0, 0, 0], 5)
Expected Output: [0, 0, 0, 0, 0]
Explanation: Every subset has sum 0, so every returned value is 0.
Hints
- If `total = sum(w)`, then every subset sum can be written as `total - removed_sum`, where `removed_sum` is the sum of the elements not chosen. So the largest subset sums correspond to the smallest removed sums.
- After sorting the weights in ascending order, you can generate the next smallest removed sum with a min-heap instead of enumerating all `2^n` subsets.