Given a positive integer N, the task is to count all possible distinct binary strings of length N such that there are no consecutive 1’s.
Input: N = 5
The non-negative integers <= 5 with their corresponding binary representations are:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only 3 has two consecutive 1’s. Therefore required count = 5
Input: N = 12
Approach: In this article, an approach using the concept of digit-dp is discussed.
- Similar to the digit-dp problem, a 3-dimensional table is created here to store the computed values. It is assumed that the N < 231 – 1, and the range of every number is only 2 (Either 0 or 1). Therefore, the dimensions of the table are taken as 32 x 2 x 2.
- After constructing the table, the given number is converted to a binary string.
- Then, the number is iterated. For every iteration:
- Check if the previous digit is a 0 or 1.
- If it is a 0, then the present number can either be a 0 or 1.
- But if the previous number is 1, then the present number has to be 0 because we can’t have two consecutive 1’s in the binary representation.
- Now, the table is exactly filled like the digit-dp problem.
Below is the implementation of the above approach
Time Complexity: O(L * log(N))
- O(log(N)) to convert the number from Decimal to binary.
- O(L) to fill the table, where L is the length of the binary form.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Count number of binary strings without consecutive 1's
- Count of Binary strings of length N having atmost M consecutive 1s or 0s alternatively exactly K times
- Find the number of binary strings of length N with at least 3 consecutive 1s
- Count number of binary strings of length N having only 0's and 1's
- Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1's
- Generate all binary strings without consecutive 1's
- Count strings with consecutive 1's
- Count of sub-strings with equal consecutive 0's and 1's
- Count binary strings with twice zeros in first half
- Count of non-overlapping sub-strings "101" and "010" in the given binary string
- Count of strings possible by replacing two consecutive same character with new character
- Python | Check if there are K consecutive 1's in a binary number
- Find consecutive 1s of length >= n in binary representation of a number
- Count binary strings with k times appearing adjacent two set bits
- Count of distinct XORs formed by rearranging two Binary strings
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.