Valid Binary Strings With Cost Limit Problem
#3955
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3955.
You are given two integers n and k.
The cost of a binary string s is defined as the sum of all indices i (0-based) such that s[i] == '1'.
A binary string is considered valid if:
- It does not contain two consecutive
'1'characters. - Its cost is less than or equal to
k.
Return a list of all valid binary strings of length n in any order.
Example 1:
Input: n = 3, k = 1
Output: ["000","010","100"]
Explanation:
The binary strings of length 3 without consecutive '1' characters are:
- "000" : cost = 0
- "100" : cost = 0
- "010" : cost = 1
- "001" : cost = 2
- "101" : cost = 0 + 2 = 2
Among these, the strings with cost less than or equal to k = 1 are "000", "010" and "100".
Thus, the valid strings are ["000", "010", "100"].
Example 2:
Input: n = 1, k = 0
Output: ["0","1"]
Explanation:
The valid binary strings of length 1 are "0" and "1".
Thus the answer is ["0", "1"].
Constraints:
1 <= n <= 120 <= k <= n * (n - 1) / 2
Solution
Approach: DFS
Build the string from left to right with dfs(i, tot), where i is the position being filled and tot is the sum of the indices of the 1s placed so far.
- When
i == n, the string is complete: add it to the answer. - A
0can always be placed; recurse with the sametot. - A
1can be placed only if the previous character is missing or0, andtot + i <= k; recurse withtot + i.
Undo each choice after returning so the other branch starts from the same state.
Complexity: time O(n * 2^n), space O(n) besides the output.
class Solution:
def generateValidStrings(self, n: int, k: int) -> List[str]:
def dfs(i: int, tot: int):
if i >= n:
ans.append("".join(path))
return
path.append("0")
dfs(i + 1, tot)
path.pop()
if (not path or path[-1] == "0") and tot + i <= k:
path.append("1")
dfs(i + 1, tot + i)
path.pop()
ans = []
path = []
dfs(0, 0)
return ans