Skip to content
DSA Patterns
Menu
Language
Knapsack & Subset DPLC #4742 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Ones and Zeroes

Problem (restated)

Binary strings strs; budgets m zeros and n ones. Largest subset of strings formable without exceeding budgets.

Intuition

Each string is an item costing (zeros, ones) with value 1. Classic 0/1 knapsack in 2D capacity.

Approaches

2D 0/1 knapsack

Unverified
Time O(L·m·n)Space O(m·n)

Idea. dp[i][j] = max strings with ≤i zeros and ≤j ones. Iterate items reverse on capacities.

Walkthrough. strs=[“10”,“0001”,“111001”,“1”,“0”], m=5,n=3 → 4.

Trade-offs. Forward loops would reuse the same string; reverse enforces 0/1.

Solution
export function findMaxForm(strs: string[], m: number, n: number): number {
  const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
  for (const s of strs) {
    let zeros = 0, ones = 0;
    for (const c of s) if (c === "0") zeros++; else ones++;
    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]!;
}
export function findMaxForm(strs: string[], m: number, n: number): number {
  const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
  for (const s of strs) {
    let zeros = 0, ones = 0;
    for (const c of s) if (c === "0") zeros++; else ones++;
    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]!;
}

Template connection

Two capacities, zeros and ones. Each string is used once, so both capacities walk downward. dp[i][j] is the most strings that fit in i zeros and j ones.

Reflection

  • Each string is used once, so the loops over the zero budget and the one budget walk backward. dp[z][o] is the most strings that fit those budgets.
  • A forward loop counts the same string again. Skip a string whose zeros or ones exceed the budget.
  • m = 0 and n = 0 answers 1 only when an empty string is in the list. An empty list answers 0.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Ones and zeroes: pack strings into m=1 zeros and n=1 ones. Tiny set ["10","0","1"].

10
0
0
1
1
2

m=1 · n=1

Key:Active rangeMatchSettledEliminated