Ones and Zeroes (LeetCode 474): Solution and Explanation

Medium
Array
String
Dynamic Programming

You get a list of binary strings and two budgets, m zeros and n ones. Choose as many strings as possible so that, all together, they contain at most m zeros and at most n ones, and return that count.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Each string is either taken or left out, and taking it spends some of two budgets. That is the 0/1 knapsack problem with two weight dimensions and a value of 1 per item. Brute force would try all 2^L subsets of the L strings, which explodes quickly.

In knapsack style, define dp[i][j] as the most strings you can pick using at most i zeros and j ones from the strings processed so far. When a new string with zeros zeros and ones ones arrives, for every budget large enough to afford it you either skip it, keeping dp[i][j], or take it, which gives dp[i - zeros][j - ones] + 1. Take the better of the two.

The table is reused across strings, so the order of updates matters. If you filled budgets from small to large, dp[i - zeros][j - ones] might already include the current string, and you would effectively take it twice. Walking both budgets downward guarantees the smaller cells you read still reflect only the earlier strings. This is the same backward-loop trick used to compress the classic one-dimensional 0/1 knapsack, just applied to two capacity dimensions at once, and it lets one table serve for the whole input instead of keeping a layer per string.

Approach: 2D 0/1 knapsack DP

  1. Create an (m + 1) by (n + 1) table of zeros.
  2. For each string, count its zeros and ones.
  3. Loop i from m down to zeros and j from n down to ones, the budgets that can afford this string.
  4. Set dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1).
  5. After all strings, return dp[m][n].

Step-by-step example

strs = ["10", "0", "1"], m = 1, n = 1
  1. The table is 2 by 2 and starts as all zeros.
  2. String "10" costs one zero and one one, so only dp[1][1] can afford it and becomes dp[0][0] + 1 = 1.
  3. String "0" costs one zero. dp[1][1] stays max(1, dp[0][1] + 1) = 1, and dp[1][0] becomes dp[0][0] + 1 = 1.
  4. String "1" costs one one. dp[1][1] becomes max(1, dp[1][0] + 1) = 2, and dp[0][1] becomes 1.
  5. The answer is dp[1][1] = 2, picking "0" and "1" instead of the single string "10".

Code: Python, Java, C++

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
5        for s in strs:
6            zeros = s.count('0')
7            ones = s.count('1')
8
9            for i in range(m, zeros - 1, -1):
10                for j in range(n, ones - 1, -1):
11                    dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
12
13        return dp[m][n]

Time and space complexity

Time

O(L × m × n + S)

For each of the L strings the code updates up to (m + 1) × (n + 1) cells, and counting characters costs S, the total length of all strings.

Space

O(m × n)

One table of (m + 1) × (n + 1) entries is reused for every string.

Other approaches

3D DP over strings (time O(L × m × n), space O(L × m × n))

Keep a separate layer per string, dp[k][i][j], built from layer k - 1. It is easier to reason about because no backward loop is needed, but uses L times more memory.

Memoized recursion (time O(L × m × n), space O(L × m × n))

Recurse on (index, zeros left, ones left), choosing to take or skip each string, and cache results. Same bounds, more overhead.

Common mistakes

  • Iterating the budgets upward. The current string can then be counted more than once, turning the problem into an unbounded knapsack and overcounting.
  • Mixing up which budget is zeros and which is ones. m limits zeros and n limits ones, and the table indices must follow that.
  • Initializing the table to negative infinity as in exact-capacity knapsack. Here m and n are upper limits, not exact totals, so every cell must start at 0.
  • Starting the inner loops at 0 and checking bounds inside. It works but is easy to get wrong; stopping at zeros and ones avoids negative indices.

Frequently asked questions

Why is Ones and Zeroes a knapsack problem?

Each string is an item you take or skip, it costs zeros and ones from two budgets, and each one is worth 1. Maximizing the count under both limits is a two-dimensional 0/1 knapsack.

Why iterate the DP backward?

The same table is reused for each string. Going from high budgets to low ensures the cell you read has not been updated for the current string, so each string is used at most once.

What is the time complexity of Ones and Zeroes?

O(L × m × n) plus the time to count characters, where L is the number of strings. Space is O(m × n).

Can greedy solve Ones and Zeroes?

No. Picking by length or by fewest zeros can waste the budget that matters, and only the DP compares every combination of budgets.