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?
- 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)
- B. Knapsack DP over W is O(n·W) and W is small
- C. Greedy by weight is optimal for counting
- 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
- Problem: For each element of an array of n = 10⁵, count how many elements to its right are smaller. What is the best complexity?
- Problem: A grid of R × C = 10³ × 10³ heights; find the minimum possible 'maximum step height' along any path from top-left to…
- Problem: Count distinct values in every window of size k over n = 10⁶ values. What is the optimal complexity?
- Problem: n = 10⁵ cities connected by roads that are added one at a time; after each addition report the number of connected components…
- Problem: Find the longest substring that appears at least twice in a string of length 10⁵. Which approach is efficient?
- Problem: A recursive solution for 'number of ways to partition n into parts' is memoised on (n, largest part allowed). With n ≤ 1000, how…