#474
Ones and Zeroes
MediumArrayStringDynamic ProgrammingDynamic ProgrammingCombinatorial Optimization
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m * n * k) |
| Space | O(1) | O(m * n) |
💡
Intuition
Time O(m * n * k)Space O(m * n)
The optimal approach uses dynamic programming to keep track of the maximum size of subsets that can be formed with given limits of 0's and 1's. This significantly reduces the number of redundant calculations compared to the brute force method.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a 2D DP array where dp[i][j] represents the maximum size of the subset with i 0's and j 1's.
- 2Step 2: Iterate through each string in the input array and count its 0's and 1's.
- 3Step 3: Update the DP array in reverse order to avoid overwriting values that are needed for calculations in the same iteration.
solution.py9 lines
1def findMaxForm(strs, m, n):
2 dp = [[0] * (n + 1) for _ in range(m + 1)]
3 for s in strs:
4 count_0 = s.count('0')
5 count_1 = s.count('1')
6 for i in range(m, count_0 - 1, -1):
7 for j in range(n, count_1 - 1, -1):
8 dp[i][j] = max(dp[i][j], dp[i - count_0][j - count_1] + 1)
9 return dp[m][n]ℹ
Complexity note: The time complexity is O(m * n * k) where k is the number of strings. This is because we iterate through each string and update the DP table, which has dimensions m and n.
- 1Using dynamic programming reduces redundant calculations and improves efficiency.
- 2Understanding how to manage state in a DP table is crucial for solving similar problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.