Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: n ≤ 40 items with weights up to 10⁹; count subsets with total weight ≤ W. Why is meet-in-the-middle preferred here?

  1. A. 2⁴⁰ ≈ 10¹² is too many, but splitting into two halves of 2²⁰ ≈ 10⁶ subsets each, sorting one half and binary searching gives O(2^(n/2) · n)
  2. B. Knapsack DP over W is O(n·W) and W is small
  3. C. Greedy by weight is optimal for counting
  4. D. Bitmask DP over 2⁴⁰ states fits in memory

Correct answer: A. 2⁴⁰ ≈ 10¹² is too many, but splitting into two halves of 2²⁰ ≈ 10⁶ subsets each, sorting one half and binary searching gives O(2^(n/2) · n)

Weights up to 10⁹ make a capacity DP impossible. Enumerating each half (2²⁰ sums), sorting one, and for each sum of the other half counting partners ≤ W − s by binary search is about 2 × 10⁷ · log operations.

More Coding Interview Problems questions

Exams that ask this topic