LeetCode #474 Medium

Ones and Zeroes

Ones and Zeroes is LeetCode 474 (Medium). You get an array strs of binary strings and two limits, m and n. Pick as many strings as you can so that, all together, they contain at most m zeros and at most n ones. Return how many strings you picked.

  • Each string is used at most once.
  • The letters inside a string do not matter, only how many 0s and how many 1s it has.
  • With up to 600 strings, trying every subset is out of the question, but m and n are at most 100, so a table over the two limits is small.
Constraints
  • 1 <= strs.length <= 600
  • 1 <= strs[i].length <= 100
  • strs[i] consists only of digits '0' and '1'.
  • 1 <= m, n <= 100
dynamic-programmingstrings
Open on LeetCode ↗
02

Intuition

Turn each string into a price with two parts: its count of 0s and its count of 1s. Now the question is the 0/1 knapsack with two wallets instead of one, and every item is worth exactly 1.

Keep a grid where dp[i][j] is the most strings you can afford with i zeros and j ones to spend. When a new string arrives, each cell either ignores it or buys it, and buying it leaves the budget (i − zeros, j − ones), whose best count is already in the grid. Taking the larger of the two keeps every cell correct after every string.

How to spot this pattern

Choose a subset, each item at most once, while two separate totals stay under two separate limits. That is a knapsack whose capacity is a pair of numbers, so the table gets one dimension per limit.

03

Approach

Try it first

Before reading on, ask what two numbers describe what is left of your budget after some choices. Write the best count for that budget in terms of whether you take one string. Aim for O(L · m · n), where L is the number of strings.

1

Count each string once

For every string, count its zeros; its ones are the length minus that. From here on the string is just the pair (zeros, ones), because the order of its characters never affects the budget.

2

A grid over both budgets

Make dp with m + 1 rows and n + 1 columns, all 0. Before any string is seen, no budget can buy anything, so 0 is correct for every cell.

3

Buy or skip, from the largest budget down

For each string, visit i from m down to zeros and j from n down to ones, and set dp[i][j] to the larger of itself and dp[i − zeros][j − ones] + 1. Going downwards means the smaller cell you read has not been updated for this string yet, so the string is counted at most once.

4

Read the full budget

After the last string, dp[m][n] is the most strings that fit in m zeros and n ones. A string with more zeros than m or more ones than n never enters the loops, so it is skipped automatically.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
▶3 dp = [[0] * (n + 1) for _ in range(m + 1)]
▶4 for s in strs:
▶5 zeros = s.count("0")
▶6 ones = len(s) - zeros
▶7 for i in range(m, zeros - 1, -1):
▶8 for j in range(n, ones - 1, -1):
▶9 dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
▶10 return dp[m][n]
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓000100budget being updatedbudget left after buyingevery budget starts at 0 strings
m1
n1
Each cell answers one question: with this many zeros and this many ones to spend, how many strings can I buy? Before any string is seen the answer is 0 everywhere.
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓000100budget being updatedbudget left after buying“10” costs 1 zero and 1 one
zeros1
ones1
Only the two counts matter. Next, every budget that can afford this string asks whether buying it beats what it already has, starting from the largest budget.
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓000101budget being updatedbudget left after buying1 zero, 1 one: buy → 1, beats 0
budget1, 1
if bought1
now1
Buying “10” leaves 0 zeros and 0 ones, which can buy 0 strings from the earlier ones, so buying gives 1. That beats 0, so the cell becomes 1. The smaller budget was read before this string touched it, so the string is counted once.
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓000101budget being updatedbudget left after buying“0” costs 1 zero and 0 ones
zeros1
ones0
Only the two counts matter. Next, every budget that can afford this string asks whether buying it beats what it already has, starting from the largest budget.
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓000101budget being updatedbudget left after buying1 zero, 1 one: buy → 1, keep 1
budget1, 1
if bought1
now1
Buying “0” leaves 0 zeros and 1 one, which can buy 0 strings from the earlier ones, so buying gives 1. That does not beat 1, so the cell keeps 1. The smaller budget was read before this string touched it, so the string is counted once.
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓000111budget being updatedbudget left after buying1 zero, 0 ones: buy → 1, beats 0
budget1, 0
if bought1
now1
Buying “0” leaves 0 zeros and 0 ones, which can buy 0 strings from the earlier ones, so buying gives 1. That beats 0, so the cell becomes 1. The smaller budget was read before this string touched it, so the string is counted once.
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓000111budget being updatedbudget left after buying“1” costs 0 zeros and 1 one
zeros0
ones1
Only the two counts matter. Next, every budget that can afford this string asks whether buying it beats what it already has, starting from the largest budget.
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓000112budget being updatedbudget left after buying1 zero, 1 one: buy → 2, beats 1
budget1, 1
if bought2
now2
Buying “1” leaves 1 zero and 0 ones, which can buy 1 string from the earlier ones, so buying gives 2. That beats 1, so the cell becomes 2. The smaller budget was read before this string touched it, so the string is counted once.
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓001112budget being updatedbudget left after buying0 zeros, 1 one: buy → 1, beats 0
budget0, 1
if bought1
now1
Buying “1” leaves 0 zeros and 0 ones, which can buy 0 strings from the earlier ones, so buying gives 1. That beats 0, so the cell becomes 1. The smaller budget was read before this string touched it, so the string is counted once.
strings“10”1 zero, 1 one“0”1 zero, 0 ones“1”0 zeros, 1 oneones you may spend →01zeros ↓001112budget being updatedbudget left after buyinganswer: 2 strings
return2
The bottom-right cell has the full budget of 1 zero and 1 one, and it has seen every string, so it holds the answer.
05

Common pitfalls

Looping the budgets upwards

✗ Wrong
for i in range(zeros, m + 1):
    for j in range(ones, n + 1):
✓ Right
for i in range(m, zeros - 1, -1):
    for j in range(n, ones - 1, -1):

Upwards, a cell can read a smaller cell that this same string already updated, so one string is bought twice. For strs = ["0"], m = 2, n = 1 the upward loop returns 2, but there is only one string.

Picking short strings first

✗ Wrong
sort strs by length, take while both budgets last
✓ Right
fill the two-budget grid

Length ignores which budget a string drains. For strs = ["00", "10", "01"], m = 2, n = 3 all three have length 2; taking "00" first spends both zeros and nothing else fits, giving 1, while "10" and "01" together give 2.

06

Edge cases

A string that alone is over a limit, like "000" with m = 2

The zeros loop starts at 2 and stops before reaching 3, so the string never touches the grid. No special check is needed.

07

Complexity

Time
O(L · m · n + total length)
Space
O(m · n)
Each of the L strings sweeps at most (m + 1)(n + 1) cells, about 10,000, so 600 strings cost about 6 million updates. Counting characters adds the total length of all strings. The grid is reused for every string, so memory does not grow with L.
08

Ones and Zeroes FAQ

Can the grid have a third dimension for the string index?

Yes: dp[k][i][j] for the first k strings, which lets you loop the budgets in any direction. It uses about 600 × 101 × 101 cells, roughly 6 million, so the two-dimensional grid is preferred.

Which problems use the same trick with one budget?

Partition Equal Subset Sum asks whether a subset hits an exact sum with one budget, and the 0/1 knapsack maximises value under one weight limit. Adding a limit adds a dimension to the table.