LeetCodee

474. Ones and Zeroes

Jump to Solution: Python Java C++ JavaScript C#

Problem Description

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 total.

Example 1:

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.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.

Example 2:

Input: strs = ["10","0","1"], m = 1, n = 1
Output: 2
Explanation: The largest subset is {"0", "1"}, so the answer is 2.

Constraints:

  • 1 <= strs.length <= 600
  • 1 <= strs[i].length <= 100
  • strs[i] consists only of digits '0' and '1'
  • 1 <= m, n <= 100

Solution

Python Solution

class Solution:
    def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
        # dp[i][j] represents the maximum number of strings that can be formed with i 0's and j 1's
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        
        for s in strs:
            # Count number of zeros and ones in current string
            zeros = s.count('0')
            ones = s.count('1')
            
            # Update dp array from bottom-right to top-left
            for i in range(m, zeros - 1, -1):
                for j in range(n, ones - 1, -1):
                    dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
        
        return dp[m][n]

Time Complexity: O(L × m × n)

Where L is the length of strs array, and m and n are the given constraints.

Space Complexity: O(m × n)

For the dynamic programming table.

Java Solution

class Solution {
    public int findMaxForm(String[] strs, int m, int n) {
        // dp[i][j] represents the maximum number of strings that can be formed with i 0's and j 1's
        int[][] dp = new int[m + 1][n + 1];
        
        for (String s : strs) {
            int[] count = countZerosOnes(s);
            int zeros = count[0], ones = count[1];
            
            // Update dp array from bottom-right to top-left
            for (int i = m; i >= zeros; i--) {
                for (int j = n; j >= ones; j--) {
                    dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
                }
            }
        }
        
        return dp[m][n];
    }
    
    private int[] countZerosOnes(String s) {
        int[] count = new int[2];
        for (char c : s.toCharArray()) {
            count[c - '0']++;
        }
        return count;
    }
}

Time Complexity: O(L × m × n)

Where L is the length of strs array, and m and n are the given constraints.

Space Complexity: O(m × n)

For the dynamic programming table.

C++ Solution

class Solution {
public:
    int findMaxForm(vector& strs, int m, int n) {
        // dp[i][j] represents the maximum number of strings that can be formed with i 0's and j 1's
        vector> dp(m + 1, vector(n + 1, 0));
        
        for (const string& s : strs) {
            int zeros = count(s.begin(), s.end(), '0');
            int ones = s.length() - zeros;
            
            // Update dp array from bottom-right to top-left
            for (int i = m; i >= zeros; i--) {
                for (int j = n; j >= ones; j--) {
                    dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1);
                }
            }
        }
        
        return dp[m][n];
    }
};

Time Complexity: O(L × m × n)

Where L is the length of strs array, and m and n are the given constraints.

Space Complexity: O(m × n)

For the dynamic programming table.

JavaScript Solution

/**
 * @param {string[]} strs
 * @param {number} m
 * @param {number} n
 * @return {number}
 */
var findMaxForm = function(strs, m, n) {
    // dp[i][j] represents the maximum number of strings that can be formed with i 0's and j 1's
    const dp = Array(m + 1).fill().map(() => Array(n + 1).fill(0));
    
    for (const s of strs) {
        const zeros = (s.match(/0/g) || []).length;
        const ones = s.length - zeros;
        
        // Update dp array from bottom-right to top-left
        for (let i = m; i >= zeros; i--) {
            for (let j = n; j >= ones; j--) {
                dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
            }
        }
    }
    
    return dp[m][n];
};

Time Complexity: O(L × m × n)

Where L is the length of strs array, and m and n are the given constraints.

Space Complexity: O(m × n)

For the dynamic programming table.

C# Solution

public class Solution {
    public int FindMaxForm(string[] strs, int m, int n) {
        // dp[i][j] represents the maximum number of strings that can be formed with i 0's and j 1's
        int[,] dp = new int[m + 1, n + 1];
        
        foreach (string s in strs) {
            int zeros = s.Count(c => c == '0');
            int ones = s.Length - zeros;
            
            // Update dp array from bottom-right to top-left
            for (int i = m; i >= zeros; i--) {
                for (int j = n; j >= ones; j--) {
                    dp[i,j] = Math.Max(dp[i,j], dp[i - zeros,j - ones] + 1);
                }
            }
        }
        
        return dp[m,n];
    }
}

Time Complexity: O(L × m × n)

Where L is the length of strs array, and m and n are the given constraints.

Space Complexity: O(m × n)

For the dynamic programming table.

Approach Explanation

The solution uses dynamic programming with a 2D array approach:

  1. Key Insights:
    • 0/1 Knapsack variation
    • State representation
    • Bottom-up approach
    • Optimal substructure
  2. Algorithm Steps:
    • Initialize DP table
    • Process each string
    • Count zeros and ones
    • Update states

Implementation Details:

  • 2D array creation
  • String counting
  • State transitions
  • Maximum subset tracking

Optimization Insights:

  • Space optimization
  • Efficient counting
  • Early termination
  • Memory reuse

Edge Cases:

  • Empty strings
  • Single character
  • Maximum constraints
  • Zero capacity