Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created November 11, 2025 18:09
Show Gist options
  • Select an option

  • Save Ifihan/9534a57a2224328d78fc2223546df577 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/9534a57a2224328d78fc2223546df577 to your computer and use it in GitHub Desktop.
Ones and Zeroes

Question

Approach

I treat this as a 0/1 knapsack with two capacity dimensions: number of zeros m and number of ones n. For each string I count how many zeros and ones it needs. I maintain a 2D DP table dp[i][j] = maximum number of strings selectable using at most i zeros and j ones. For each string I update the DP in reverse (from m down to zeros and n down to ones) so each string is used at most once. The answer is dp[m][n].

Implementation

class Solution:
    def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        
        for s in strs:
            zeros = s.count('0')
            ones = len(s) - zeros
            for i in range(m, zeros - 1, -1):
                for j in range(n, ones - 1, -1):
                    dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
        
        return dp[m][n]

Complexities

  • Time: O(len(strs) * m * n)
  • Space: O(m * n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment