Ones and Zeroes — LeetCode 474 Python Solution

MediumArrayStringDynamic Programming
Problem
#474
Reading time
2 min

The problem

You are given an array of binary strings strs and two integers m and n. Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.

Example

Input
strs = ["10","0001","111001","1","0"], m = 5, n = 3
Output
4
Explanation
The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.

Python solution

Python
class Solution:
    def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
        sz = len(strs)
        f = [[[0] * (n + 1) for _ in range(m + 1)] for _ in range(sz + 1)]
        for i, s in enumerate(strs, 1):
            a, b = s.count("0"), s.count("1")
            for j in range(m + 1):
                for k in range(n + 1):
                    f[i][j][k] = f[i - 1][j][k]
                    if j >= a and k >= b:
                        f[i][j][k] = max(f[i][j][k], f[i - 1][j - a][k - b] + 1)
        return f[sz][m][n]

Complexity

MeasureComplexity
TimeO(sz \times m \times n)
SpaceO(sz \times m \times n), where sz is the length of the array strs, and m and n are the upper limits on the number of zeros and ones, respectively auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 474. Ones and Zeroes is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 474. Ones and Zeroes?
LeetCode 474. Ones and Zeroes is rated Medium on LeetCode.
What is the time complexity of LeetCode 474. Ones and Zeroes?
The Python solution on this page runs in O(sz \times m \times n).
What is the space complexity of LeetCode 474. Ones and Zeroes?
The Python solution on this page uses O(sz \times m \times n), where sz is the length of the array strs, and m and n are the upper limits on the number of zeros and ones, respectively auxiliary space.
What topics does LeetCode 474. Ones and Zeroes cover?
LeetCode 474. Ones and Zeroes is tagged Array, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview