The Ones and Zeroes problem gives you a list of binary strings and two limits m (max zeros) and n (max ones). Find the maximum number of strings you can include such that the total zeros ≤ m and total ones ≤ n. This coding problem is a 2D variant of the 0/1 knapsack problem. The array, string, and dynamic programming interview pattern is the core.
Uber, Meta, Google, and Bloomberg ask this because it extends 0/1 knapsack to two resource dimensions (zeros and ones). The ability to generalize knapsack DP to multiple constraints is tested. Each string is an "item" with two "weights" (zeros count and ones count) and "value" 1.
2D 0/1 knapsack DP. dp[i][j] = maximum strings using exactly i zeros and j ones. For each string with z zeros and o ones: update DP in reverse: dp[i][j] = max(dp[i][j], dp[i-z][j-o]+1) for i from m down to z, j from n down to o.
strs=["10","0001","111001","1","0"], m=5, n=3.
2D knapsack problems always use reverse DP iteration to enforce the "at most once" constraint. The pattern: outer loop over items, inner two loops from max capacity down to item's weight. Practice 1D knapsack first, then generalize to 2D — the structure is identical with an extra dimension. This technique applies to "select items under two resource limits" in scheduling, resource allocation, and budget problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sentence Screen Fitting | Medium | Solve | |
| Longest Unequal Adjacent Groups Subsequence II | Medium | Solve | |
| Number of Ways to Form a Target String Given a Dictionary | Hard | Solve | |
| Delete Columns to Make Sorted III | Hard | Solve | |
| Minimum Time to Make Rope Colorful | Medium | Solve |