Generate Binary Strings Without Adjacent Zeros - Problem

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.

In other words, no two consecutive zeros ("00") are allowed in any valid binary string.

Input & Output

Example 1 — Basic Case
$ Input: n = 3
Output: ["010","011","101","110","111"]
💡 Note: All valid 3-length binary strings without consecutive zeros. Note that "000", "001", and "100" are invalid because they contain "00".
Example 2 — Minimum Size
$ Input: n = 1
Output: ["0","1"]
💡 Note: For length 1, both "0" and "1" are valid since there are no substrings of length 2 to check.
Example 3 — Small Case
$ Input: n = 2
Output: ["01","10","11"]
💡 Note: For length 2, "00" is invalid (contains consecutive zeros), but "01", "10", and "11" are all valid.

Constraints

  • 1 ≤ n ≤ 20

Visualization

Tap to expand
Generate Binary Strings Without Adjacent Zeros INPUT n = 3 Length of binary string Constraint: No "00" allowed "101" OK - Valid "100" Invalid Fibonacci Pattern: n=1: 2 strings n=2: 3 strings n=3: 5 strings ALGORITHM STEPS 1 Initialize Start with "0" and "1" 2 DP Transition If ends with 1: add 0 or 1 If ends with 0: add only 1 3 Build Strings Extend until length n 4 Collect Results Return all valid strings Build Tree (n=3): "0" "1" "01" "10" "11" "010" "011" "101" "110" "111" FINAL RESULT Valid Binary Strings: "010" "011" "101" "110" "111" Output Array: ["010","011","101","110","111"] 5 Valid Strings Fibonacci Count: F(n+2) = F(n+1) + F(n) F(5) = F(4) + F(3) = 3 + 2 = 5 Key Insight: The problem follows a Fibonacci pattern! After character '1', we can append either '0' or '1'. After '0', we can only append '1' (to avoid "00"). This branching creates Fibonacci growth: count(n) = count(n-1) + count(n-2). Time: O(F(n+2)) where F is Fibonacci. Space: O(n) for recursion depth or O(F(n+2)) for storing results. TutorialsPoint - Generate Binary Strings Without Adjacent Zeros | Dynamic Programming with Fibonacci Pattern
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
12.5K Views
Medium Frequency
~15 min Avg. Time
342 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