|
| 1 | +# Ones and Zeroes (Medium) |
| 2 | + |
| 3 | +**Problem ID:** 474 |
| 4 | +**Date:** 2025-11-11 |
| 5 | +**Link:** https://leetcode.com/problems/ones-and-zeroes/ |
| 6 | + |
| 7 | +## Approach |
| 8 | + |
| 9 | +To solve the "Ones and Zeroes" problem, we can utilize a dynamic programming approach similar to the "0/1 Knapsack" problem. The main idea is to maintain a 2D DP table that keeps track of the maximum size of the subset of binary strings that can be formed with a given number of zeros and ones. |
| 10 | + |
| 11 | +### Approach: |
| 12 | + |
| 13 | +1. **Count Zeros and Ones**: For each binary string in the input array, count the number of zeros and ones. This can be done using simple iteration over each string. |
| 14 | + |
| 15 | +2. **Dynamic Programming Table**: Create a 2D DP array `dp` where `dp[i][j]` represents the maximum size of the subset that can be formed with at most `i` zeros and `j` ones. |
| 16 | + |
| 17 | +3. **Initialization**: Initialize the DP table with zeros. The base case is `dp[0][0] = 0`, meaning with zero zeros and zero ones, the maximum subset size is zero. |
| 18 | + |
| 19 | +4. **Filling the DP Table**: |
| 20 | + - Iterate over each string and its corresponding count of zeros (`zero_count`) and ones (`one_count`). |
| 21 | + - Update the DP table in reverse order (from `m` to `zero_count` and from `n` to `one_count`). This prevents overwriting results of the current iteration. |
| 22 | + - For each valid combination of zeros and ones, update the DP value as follows: |
| 23 | + ``` |
| 24 | + dp[i][j] = max(dp[i][j], dp[i - zero_count][j - one_count] + 1) |
| 25 | + ``` |
| 26 | + - This means we can either choose to include the current string (hence the `+1`) or not include it. |
| 27 | +
|
| 28 | +5. **Result Extraction**: The result will be found at `dp[m][n]`, which gives the size of the largest subset that can be formed with at most `m` zeros and `n` ones. |
| 29 | +
|
| 30 | +### Data Structures: |
| 31 | +- A 2D list (or array) for the DP table, where dimensions are `(m + 1) x (n + 1)`. |
| 32 | +
|
| 33 | +### Complexity: |
| 34 | +- **Time Complexity**: O(S * m * n), where `S` is the number of strings in `strs`. This is due to iterating through each string and updating the DP table. |
| 35 | +- **Space Complexity**: O(m * n) for the DP table. |
| 36 | +
|
| 37 | +This approach efficiently computes the maximum subset size while adhering to the constraints on the number of zeros and ones, leveraging the principles of dynamic programming to build up solutions from smaller subproblems. |
0 commit comments