Ones and Zeroes solution explained
Ones and Zeroes is a 0/1 knapsack with two capacities: each string costs some zeros and some ones, every string is worth 1, and you want the most strings that fit both budgets. Keep a table best[z][o] for the largest count that fits in z zeros and o ones, and for each string update it from the top budgets down so the string is used at most once. That runs in O(L * Z * O) time and O(Z * O) memory, where L is the number of strings.
By Evin JohnPublished 8 min read
The problem in plain words
You get a list of strings made only of the characters 0 and 1, and two limits: Z, the most zero characters you may use, and O, the most one characters. Choose a group of the strings (each one at most once) so that the zeros across the whole group add up to no more than Z and the ones add up to no more than O. Return the size of the largest such group. The content of a string does not matter beyond its two counts, so the first move is to turn every string into a pair: (zeros, ones).
| Strings | Z, O | Answer | One best group |
|---|---|---|---|
| 110, 0, 01, 1000, 11, 0 | 3, 2 | 3 | 0, 0, 11 (2 zeros, 2 ones) |
| 110, 0, 01, 1000, 11, 0 | 4, 4 | 4 | 0, 0, 01, 11 (3 zeros, 3 ones) |
| 111, 0 | 0, 3 | 1 | 111, since 0 needs a zero we cannot spend |
| (none) | 3, 3 | 0 | Nothing to pick |
What the interviewer is checking
This problem tests whether you can recognise a knapsack when it is wearing a disguise. Nothing in the prompt says weight or value. The clue is the shape: a set of items, a take-it-or-leave-it choice for each, and a capacity you must not exceed. Here the capacity has two dimensions instead of one, and the value of every item is the same. Interviewers want to hear that mapping out loud, then a correct table definition, then the reason the loops run downward. Candidates who reach for a greedy rule (shortest strings first, or fewest ones first) usually get stuck on a counterexample, and spotting that early is part of the signal.
Questions worth asking before you code
- Can a string be empty? An empty string costs nothing, so it should always be picked. The table code handles it without a special case.
- Can the same string appear twice in the list? Yes, and each copy is a separate item that may be picked once.
- Is the answer the count or the actual strings? Usually the count. Rebuilding the group needs the full three-dimensional table or a separate choice record.
- How large are Z and O? The table has (Z + 1) * (O + 1) cells, so a budget in the millions would need a different idea.
Brute force: try every group
The direct approach enumerates subsets. Count the zeros and ones in each string once, then test groups from the largest size down and return the first size where some group fits both limits. It is a fine first sentence because it is obviously correct and it shows you understand the constraint, but there are 2^L groups. For 20 strings that is about a million checks; for a few hundred it will never finish.
@@ones-and-zeroes/slow.py@@The pattern: knapsack with two capacities
Think of the classic knapsack table, where entry best[i][c] is the best value using the first i items within capacity c. Each item either stays out (copy the entry above) or goes in (take the entry for the remaining capacity and add the item's value). Ones and Zeroes has two capacities, so the table grows a dimension: best[i][z][o]. Every string has value 1, so going in means 1 + best[i - 1][z - zeros][o - ones], and the answer is best[L][Z][O].
The first dimension only ever looks one row back, so it can be dropped. Keep a single two-dimensional table best[z][o] and update it in place, string by string. The catch is order. If you sweep z and o upward, the cell for a smaller budget may already include the current string when a larger budget reads it, and that string gets counted twice. Sweeping both budgets from the top down means every read sees the value from before this string was considered, which is exactly the old row of the three-dimensional table.
@@ones-and-zeroes/fast.py@@The JavaScript version is a line-for-line port. Counting zeros with a loop avoids building a new array for each string, and the ones count is simply the length minus the zeros. Every cell stays a small integer, so there is no overflow to worry about.
@@ones-and-zeroes/fast.js@@Walking through a small case
Take the first row of the table above: strings 110, 0, 01, 1000, 11, 0 with Z = 3 and O = 2. As pairs they are (1, 2), (1, 0), (1, 1), (3, 1), (0, 2), (1, 0). After 110, every cell with at least one zero and two ones holds 1. The first 0 lifts every cell with a zero to at least 1, and cell (2, 2) to 2 (0 plus 110). The 01 string adds nothing new at the corner, and 1000 fits only at z = 3 where it cannot beat what is there. The 11 string costs no zeros, so cell (1, 2) becomes best[1][0] + 1 = 2. The last 0 lifts cell (2, 2) to 3 by reading (1, 2), and it lifts the corner best[3][2] to 3 by reading the value (2, 2) had before this string, the group 0 plus 110. Both 0, 0, 11 and 0, 110, 0 are groups of three, and no group of four fits.
Complexity
| Approach | Time | Extra memory | When it fits |
|---|---|---|---|
| Every subset | O(2^L * L) | O(L) | Up to about 20 strings |
| Three-dimensional table | O(L * Z * O + S) | O(L * Z * O) | When you also need to rebuild the chosen group |
| Rolling two-dimensional table | O(L * Z * O + S) | O(Z * O) | The usual expected answer |
| Memoized recursion on (index, z, o) | O(L * Z * O + S) | O(L * Z * O) plus call stack | Fine to explain; deep recursion in Python for long lists |
S, the total length, appears because each string has to be scanned once to count its characters. A small speed-up is to skip strings whose zeros exceed Z or ones exceed O before entering the loops, since they can never be picked.
Edge cases to test
- An empty list returns 0.
- Both budgets 0: only empty strings can be picked.
- One budget is 0, such as Z = 0: only strings made entirely of 1 qualify.
- Many identical strings, such as six copies of 0 with Z = 4: the answer is capped by the budget, here 4.
- A string longer than both budgets combined, which should simply be ignored.
- Budgets much larger than the total counts, where the answer is every string.
Mistakes that cost points
- Sweeping the budgets upward in the rolling table. Each string turns into an unlimited supply, which is the unbounded knapsack and gives answers that are too large.
- Sorting by length and taking the shortest strings. A short string can waste the scarcer character; a counterexample appears quickly with lopsided budgets.
- Mixing up which budget belongs to which character, especially when the function receives them as m and n.
- Initialising the table with -1 or infinity. With value 1 per item and a 'fits within' meaning, zero is the right starting value everywhere.
- Returning best[Z][O] from a table indexed [O][Z]. Pick one order and say it out loud.
How to explain it out loud
Fictional example
- Candidate
- Only the counts matter, so I'll turn each string into a pair of zeros and ones. Then it's a take-or-skip choice per item with two limits, which is 0/1 knapsack with two capacities and value one per item.
- Interviewer
- Why not just take the cheapest strings first?
- Candidate
- Cheap in which character? A string that's cheap in zeros can eat the ones we need for three other strings. I'd rather use the table: best of z and o is the most strings that fit, and each string either leaves it alone or adds one to the cell it came from.
- Candidate
- I'll keep it two-dimensional and walk both budgets from the top down, so a string can't be reused within its own update. That's L times Z times O time and Z times O memory.
Related problems
Last Stone Weight II is the one-capacity version in disguise: a subset-sum table hidden behind a story about smashing stones. Profitable Schemes keeps the two-dimensional table but counts the groups instead of maximising one, and caps the profit dimension. Number of Dice Rolls With Target Sum is a counting table where each step has several choices instead of take or skip. Partition Equal Subset Sum and Coin Change are the other classic knapsack drills worth pairing with this one.
Practicing this with Natively
The hard part here is saying why it is a knapsack before anyone hints at it. In a practice session on Mac or Windows, Natively can read the prompt from a screenshot of the problem, suggest the table definition if you stall, and pose the follow-ups about a greedy shortcut or rebuilding the chosen strings. Afterwards the transcript of your mock shows whether you named the pattern yourself or only arrived at it through trial and error.
Questions people ask
How do you solve Ones and Zeroes?
Treat it as a 0/1 knapsack with two capacities. Keep best[z][o], the most strings that fit in z zeros and o ones, and for each string set best[z][o] to the larger of itself and best[z - zeros][o - ones] + 1, sweeping both budgets downward.
Why do the loops in Ones and Zeroes go backwards?
Going from the largest budget down means every cell you read still holds the value from before the current string, so each string is used at most once. Going upward lets a string be added again and again.
What is the time complexity of Ones and Zeroes?
O(L * Z * O) plus the time to count characters, where L is the number of strings and Z and O are the budgets. The rolling table uses O(Z * O) memory.
Does a greedy approach work for Ones and Zeroes?
No. Taking the shortest or cheapest strings first can spend the scarcer character on one string that blocks several others. The table compares every combination of budgets instead.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
