#3211

Generate Binary Strings Without Adjacent Zeros

Medium
StringBacktrackingBit ManipulationBacktrackingDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use backtracking to build valid strings directly, avoiding invalid combinations from the start.

⚙️

Algorithm

3 steps
  1. 1Step 1: Start with an empty string and recursively add '0' or '1'.
  2. 2Step 2: If the last character is '0', only add '1'. If it's '1', add both '0' and '1'.
  3. 3Step 3: Stop when the string reaches length n and add it to the result.
solution.py11 lines
1def generateBinaryStrings(n):
2    result = []
3    def backtrack(s):
4        if len(s) == n:
5            result.append(s)
6            return
7        backtrack(s + '1')
8        if not s or s[-1] == '1':
9            backtrack(s + '0')
10    backtrack('')
11    return result

Complexity note: Each valid string is built directly, leading to linear time complexity relative to the number of valid strings.

  • 1Adjacent zeros are the only invalid condition.
  • 2Backtracking allows for efficient string generation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.