Problem Description
Given a positive integer n, generate all binary strings of length n such that every substring of length 2 contains at least one '1'. In other words, no string contains two consecutive '0's.
Key Insights
- The only invalid scenario is when two adjacent '0's occur.
- When constructing the string, if the last character is '0', the next character must be '1'.
- Backtracking (or DFS) is an ideal approach to build the strings while enforcing the validity constraint.
Space and Time Complexity
Time Complexity: O(2^n) in the worst-case as each position may branch into 2 possibilities. Space Complexity: O(2^n * n) to store all valid strings and O(n) auxiliary space for recursion.
Solution
We solve the problem using a backtracking approach:
- Start with an empty string.
- At each step, append '0' or '1' based on the previous character:
- If the string is empty or its last character is '1', both '0' and '1' can be appended.
- If the last character is '0', only '1' can be added to avoid adjacent zeros.
- Once a string of length n is formed, add it to the results list.
- Return the list of all valid strings.
Data structures and techniques used:
- Recursion for backtracking.
- A list/array to collect valid strings.
- Conditional checks to enforce the adjacency rule.