Problem Description
You are given a positive integer n. A binary string x is valid if all substrings of x of length 2 contain at least one "1". Return all valid strings with length n, in any order.
Key Insights
- A valid binary string cannot have two consecutive '0's.
- Any valid string can end with either '0' or '1', but if it ends with '0', the previous character must be '1'.
- This problem can be approached using backtracking to generate all strings and filter out the invalid ones.
Space and Time Complexity
Time Complexity: O(2^n) - since every bit can be independently set to 0 or 1, leading to 2^n combinations. Space Complexity: O(n) - for the recursive stack and storing valid strings.
Solution
The solution employs a backtracking algorithm to construct valid binary strings recursively. Starting with an empty string, we add '0' or '1' based on the last character added:
- If the last character is '1', we can freely add either '0' or '1'.
- If the last character is '0', we can only add '1' to avoid two consecutive '0's.
- Once the string reaches the desired length n, it is added to the result list.