AlgoInsight

DSA problem

Ones and Zeroes

Medium0/1 KnapsackPattern: 0/1 Knapsacktop600GoogleAmazonMicrosoftBloombergAdobe

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. A set x is a subset of y if every element of x is also in y.

This is a two-dimensional 0/1 knapsack problem. Each binary string is an item with two capacity costs: the number of zeros it contains and the number of ones it contains. The "value" of each item is 1 (it contributes one string to the subset), and we want to maximize total value subject to two simultaneous capacity constraints (at most m zeros and at most n ones in total).

A 3D DP dp[i][j][k] where i indexes the string, j is zeros used, and k is ones used would work in O(L * m * n) time and space, but we can compress to a 2D rolling array dp[j][k] exactly like the 1D rolling trick on standard knapsack — process strings one at a time and iterate both capacity dimensions from high to low.

The optimal solution precomputes (zeros, ones) for each string in O(L) time, then for each string updates dp[j][k] = max(dp[j][k], dp[j - zeros][k - ones] + 1) for j from m down to zeros and k from n down to ones. The high-to-low iteration ensures each string is considered at most once per state, giving O(L * m * n) total time and O(m * n) extra space.

Examples

Example 1
Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3
Output: 4
Explanation: The largest subset has 4 strings, for example {"10","0001","1","0"} which uses 4 zeros and 3 ones, both within the limits.
Example 2
Input: strs = ["10","0","1"], m = 1, n = 1
Output: 2
Explanation: The largest subset is {"0","1"} which uses 1 zero and 1 one. Adding "10" would require 2 zeros and 2 ones.
Example 3
Input: strs = ["111","1000","1000","1000"], m = 9, n = 3
Output: 3
Explanation: Select three of the "1000" strings, using 9 zeros (3 each) and 3 ones (1 each) — both at the cap.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dynamic-programming0-1-knapsacktwo-dimensional-dpstring

Browse all DSA problems