KatInterview

474. Ones and Zeroes

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the size of the largest subset of binary strings that can be formed while adhering to constraints on the total number of '0's and '1's. Specifically, the chosen subset must contain at most m zeros and n ones in total.

Solution

Ones and Zeroes in Python

class Solution:
    def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
        # dp[i][j] will store the maximum number of strings that can be formed
        # with at most i zeros and j ones.
        dp = [[0] * (n + 1) for _ in range(m + 1)]

        for s in strs:
            # Count the number of zeros and ones in the current string.
            zeros = s.count('0')
            ones = s.count('1')

            # Iterate backwards from the maximum capacity to avoid using the same string multiple times.
            # This is a standard optimization for 0/1 knapsack problems.
            for i in range(m, zeros - 1, -1):
                for j in range(n, ones - 1, -1):
                    # We have two choices for the current string s:
                    # 1. Don't include s: the result is dp[i][j] (the value from before considering s).
                    # 2. Include s: the result is 1 + dp[i - zeros][j - ones].
                    # We take the maximum of these two choices.
                    dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
        
        # The final answer is the maximum number of strings we can form with at most m zeros and n ones.
        return dp[m][n]

Ones and Zeroes in Java

class Solution {
    public int findMaxForm(String[] strs, int m, int n) {
        // dp[i][j] will store the maximum number of strings that can be formed
        // with at most i zeros and j ones.
        int[][] dp = new int[m + 1][n + 1];

        for (String s : strs) {
            int zeros = 0;
            int ones = 0;
            // Count the number of zeros and ones in the current string.
            for (char c : s.toCharArray()) {
                if (c == '0') {
                    zeros++;
                } else {
                    ones++;
                }
            }

            // Iterate backwards from the maximum capacity to avoid using the same string multiple times.
            // This is a standard optimization for 0/1 knapsack problems.
            for (int i = m; i >= zeros; i--) {
                for (int j = n; j >= ones; j--) {
                    // We have two choices for the current string s:
                    // 1. Don't include s: the result is dp[i][j] (the value from before considering s).
                    // 2. Include s: the result is 1 + dp[i - zeros][j - ones].
                    // We take the maximum of these two choices.
                    dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
                }
            }
        }

        // The final answer is the maximum number of strings we can form with at most m zeros and n ones.
        return dp[m][n];
    }
}

Ones and Zeroes in C++

class Solution {
public:
    int findMaxForm(vector<string>& strs, int m, int n) {
        // dp[i][j] will store the maximum number of strings that can be formed
        // with at most i zeros and j ones.
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

        for (const string& s : strs) {
            int zeros = 0;
            int ones = 0;
            // Count the number of zeros and ones in the current string.
            for (char c : s) {
                if (c == '0') {
                    zeros++;
                } else {
                    ones++;
                }
            }

            // Iterate backwards from the maximum capacity to avoid using the same string multiple times.
            // This is a standard optimization for 0/1 knapsack problems.
            for (int i = m; i >= zeros; --i) {
                for (int j = n; j >= ones; --j) {
                    // We have two choices for the current string s:
                    // 1. Don't include s: the result is dp[i][j] (the value from before considering s).
                    // 2. Include s: the result is 1 + dp[i - zeros][j - ones].
                    // We take the maximum of these two choices.
                    dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1);
                }
            }
        }

        // The final answer is the maximum number of strings we can form with at most m zeros and n ones.
        return dp[m][n];
    }
};

Ones and Zeroes in TypeScript

function findMaxForm(strs: string[], m: number, n: number): number {
    // dp[i][j] will store the maximum number of strings that can be formed
    // with at most i zeros and j ones.
    const dp: number[][] = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0));

    for (const s of strs) {
        let zeros = 0;
        let ones = 0;
        // Count the number of zeros and ones in the current string.
        for (const char of s) {
            if (char === '0') {
                zeros++;
            } else {
                ones++;
            }
        }
        
        // Iterate backwards from the maximum capacity to avoid using the same string multiple times.
        // This is a standard optimization for 0/1 knapsack problems.
        for (let i = m; i >= zeros; i--) {
            for (let j = n; j >= ones; j--) {
                // We have two choices for the current string s:
                // 1. Don't include s: the result is dp[i][j] (the value from before considering s).
                // 2. Include s: the result is 1 + dp[i - zeros][j - ones].
                // We take the maximum of these two choices.
                dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
            }
        }
    }

    // The final answer is the maximum number of strings we can form with at most m zeros and n ones.
    return dp[m][n];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.