VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-binary-strings-without-consecutive-1s/

⇱ Generate all binary strings without consecutive 1's - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate all binary strings without consecutive 1's

Last Updated : 23 Jul, 2025

Given an integer n, the task is to generate all binary strings of size n without consecutive 1's.

Examples: 

Input : n = 4
Output : 0000 0001 0010 0100 0101 1000 1001 1010

Input : n = 3
Output : 000 001 010 100 101

Approach:

The idea is to generate all binary strings of length n without consecutive 1's using a recursive backtracking approach that explores all valid configurations. We start with a string of all '0's and then recursively consider two options for each position: either keep it as '0' or change it to '1'. When we place a '1' at any position, we skip the next position in our recursive exploration to ensure we don't create consecutive 1's.

Step by step approach:

  1. Initialize a string of length n with all zeros.
  2. For each position, explore two possibilities: keeping '0' or placing '1'.
    • When placing '1' at a position, skip the next position in recursion to avoid consecutive 1's.
  3. On reaching the end of the string, add the string to the resultant array.
  4. Use backtracking to restore the state and explore all possible paths.

Output
0000
0001
0010
0100
0101
1000
1001
1010

Interesting Fact : The count of n length strings with no consecutive 1s is equal to (n+2)-th Fibonacci Number

Time Complexity: O(n 2^n), as at each step, we can consider 0 or 1. Please note that this is an upper bound. An exact bound would be O(n F(n+2)) where F(n+2) is (n+2)th Fibonacci Number.
Auxiliary Space: O(n) due to recursion call stack.

Comment
Article Tags:
Article Tags: