Ones and Zeroes - 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 zeros ('0's) and n ones ('1's) in the subset.

A set x is a subset of a set y if all elements of x are also elements of y.

Input & Output

Example 1 — Basic Case
$ Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3
Output: 4
💡 Note: We can select at most 4 strings: "10" (1 zero, 1 one), "0001" (3 zeros, 1 one), "1" (0 zeros, 1 one), "0" (1 zero, 0 ones). Total: 5 zeros, 3 ones, which fits exactly within our limits.
Example 2 — Tight Constraints
$ Input: strs = ["10","0","1"], m = 1, n = 1
Output: 2
💡 Note: With only 1 zero and 1 one allowed, we can take either "10" (1 zero, 1 one) for count=1, OR "0" + "1" (1 zero, 1 one total) for count=2. The second option is better.
Example 3 — Edge Case
$ Input: strs = ["111","1000"], m = 3, n = 1
Output: 1
💡 Note: "111" has 3 ones but we only have budget for 1 one. "1000" has 3 zeros and 1 one, fits our constraints. Answer is 1.

Constraints

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

Visualization

Tap to expand
Ones and Zeroes - Dynamic Programming INPUT strs[] - Binary Strings "10" "0001" "111001" "1" "0" Count in each string: "10": 1 zero, 1 one "0001": 3 zeros, 1 one "111001": 2 zeros, 4 ones "1": 0 zeros, 1 one "0": 1 zero, 0 ones Constraints: m = 5 (max 0s), n = 3 (max 1s) ALGORITHM STEPS 1 Initialize 2D DP table dp[m+1][n+1] = 0s 2 For each string Count 0s and 1s 3 Update DP (reverse) dp[i][j]=max(dp,dp[i-z][j-o]+1) 4 Return dp[m][n] Max subset size DP Table Structure (6x4) 0s\1s 0 1 2 3 0 0 1 2 2 1 1 2 3 3 ... 5 1 2 3 4 dp[5][3] = 4 (answer) FINAL RESULT Optimal Subset Selected: "10" 1z, 1o "0001" 3z, 1o "1" 0z, 1o "0" 1z, 0o "111001" SKIP Total Count Verification: 0s: 1+3+0+1 = 5 (OK, m=5) 1s: 1+1+1+0 = 3 (OK, n=3) OUTPUT 4 Largest valid subset size! Key Insight: This is a 0/1 Knapsack variant with TWO capacity constraints (zeros and ones). Use 2D DP where dp[i][j] represents max strings using at most i zeros and j ones. Process strings in reverse order to avoid using the same string twice. Time: O(l*m*n), Space: O(m*n) where l = number of strings. TutorialsPoint - Ones and Zeroes | Dynamic Programming Approach
Asked in
Google 28 Facebook 15 Microsoft 12 Amazon 8
125.0K Views
Medium Frequency
~25 min Avg. Time
3.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen