Problem solution · Python

Valid Binary Strings with Cost Limit

Valid Binary Strings with Cost Limit: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
40 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Valid Binary Strings with Cost Limit, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 40 lines of Python from the credited upstream file valid-binary-strings-with-cost-limit.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeValid Binary Strings with Cost Limit · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n * 2^n)# Space: O(n) # backtrackingclass Solution(object):    def generateValidStrings(self, n, k):        """        :type n: int        :type k: int        :rtype: List[str]        """        def backtracking(total):            if len(curr) == n:                result.append("".join(curr))                return            curr.append('0')            backtracking(total)            curr.pop()            if (not curr or curr[-1] == '0') and total+len(curr) <= k:                curr.append('1')                backtracking(total+(len(curr)-1))                curr.pop()         result, curr = [], []        backtracking(0)        return result  # Time:  O(n * 2^n)# Space: O(n)# bitmasksclass Solution2(object):    def generateValidStrings(self, n, k):        """        :type n: int        :type k: int        :rtype: List[str]        """        return ["".join('1' if mask&(1<<i) else '0' for i in xrange(n)) for mask in xrange(1<<n) if mask&(mask>>1) == 0 and sum(i for i in xrange(n) if mask&(1<<i)) <= k] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗