You are given strs, a list of strings made of the digits 0 and 1, and two numbers m and n.
Pick as many strings as you can, each at most once, so that the picked strings contain no more than m zeros and no more than n ones in total. Return how many strings you picked.
Example 1
Input: strs = ["1", "00", "01"], m = 2, n = 1 Output: 2 Why: "1" and "00" use 2 zeros and 1 one; all three would need 3 zeros
2 more examples and the constraints
Example 2
Input: strs = ["0011", "01", "1", "000"], m = 3, n = 2 Output: 2 Why: "01" and "1" fit; no three strings stay within 3 zeros and 2 ones
Example 3
Input: strs = ["111"], m = 5, n = 2 Output: 0 Why: the only string needs 3 ones
Constraints
- The list holds between 1 and 600 strings
- Each string has 1 to 100 characters, all of them 0 or 1
- 1 ≤ m, n ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Knapsack table with a layer per stringO(L·m·n)
- One table, filled backwardsO(L·m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 600 strings, m = n = 100 | Verdict |
|---|---|---|---|
| Knapsack table with a layer per string | O(L·m·n) | Passes; 6 million cells of memory | |
| One table, filled backwards | O(L·m·n) | Best; same work, far less memory |
L = number of strings, m and n = the zero and one budgets.
Edge cases to test
- Nothing fits. ["111"] with only 2 ones allowed gives 0.
- Everything fits. If the budgets cover the whole list, the answer is its length.
- Duplicates. Equal strings are separate items; each can be picked once.
- One budget is the limit. ["0", "0", "0", "1"] with m = 2, n = 1 stops at 3 because of the zeros.
Common mistakes
- Looping the budgets upwards in the 2D table, which lets one string be taken many times.
- Sorting by length and taking short strings greedily.
- Sizing the table m × n instead of (m + 1) × (n + 1), losing the full budget.
How to talk through it
- 1Clarify. Is each string used at most once? Are the limits "at most", not "exactly"?
- 2Name the pattern. Each string is an item with two costs and value 1: a two-dimensional 0/1 knapsack.
- 3Define the state. dp[j][k] is the most strings that fit in j zeros and k ones.
- 4Explain the loop order. Go from the largest budget down so each string counts once.
- 5Test out loud. Run a case where nothing fits, one where all fit, and Example 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?