Generate Binary Strings Without Adjacent Zeros - Problem
Generate Valid Binary Strings

You are given a positive integer n. Your task is to generate all possible valid binary strings of length n.

A binary string is considered valid if it contains no adjacent zeros - that is, no substring "00" should appear anywhere in the string. In other words, every substring of length 2 must contain at least one "1".

Goal: Return all valid binary strings of length n in any order.

Example: For n=3, valid strings include "101", "110", "111" but not "100" (contains "00").

Input & Output

example_1.py — Python
$ Input: n = 3
Output: ["010", "011", "101", "110", "111"]
💡 Note: All binary strings of length 3 without adjacent zeros. Note that "000", "001", and "100" are invalid because they contain "00".
example_2.py — Python
$ Input: n = 1
Output: ["0", "1"]
💡 Note: For length 1, both "0" and "1" are valid since there are no adjacent characters to check.
example_3.py — Python
$ Input: n = 2
Output: ["01", "10", "11"]
💡 Note: For length 2, "00" is invalid (adjacent zeros), but "01", "10", and "11" are all valid.

Constraints

  • 1 ≤ n ≤ 18
  • The answer will contain at most 218 strings
  • Time limit: 1 second per test case

Visualization

Tap to expand
Valid Light Switch Configurations (n=3)ONOFFON= "101" ✓ONONOFF= "110" ✓OFFOFFON= "001" ❌Rule: No two adjacent switches can both be OFF
Understanding the Visualization
1
Start Empty
Begin with no switches set, can choose any state for first switch
2
Apply Rule
For each subsequent switch, check the previous switch state
3
Make Valid Choices
If previous is OFF, current must be ON. If previous is ON, current can be either
4
Complete Path
Continue until all n switches are configured
Key Takeaway
🎯 Key Insight: Use backtracking to make smart choices - when the previous character is '0', we have no choice but to place '1'. This constraint significantly reduces the search space and leads to the Fibonacci sequence pattern in the number of valid strings.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 15
23.8K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen