Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
1 to n bit numbers with no consecutive 1s in binary representation?
In this problem, we need to count binary numbers of n bits that contain no consecutive 1s in their binary representation. For example, in 3-bit binary strings, numbers like 011, 110, and 111 have consecutive 1s, while 5 numbers (000, 001, 010, 100, 101) do not have consecutive 1s.
The solution uses dynamic programming with two arrays: one tracking numbers ending with 0 and another tracking numbers ending with 1.
Syntax
int countBinaryNumbers(int n);
Algorithm
The recurrence relations are −
- endWithZero[i] = endWithZero[i-1] + endWithOne[i-1] (we can append 0 to any valid string)
- endWithOne[i] = endWithZero[i-1] (we can only append 1 to strings ending with 0)
Example: Dynamic Programming Approach
This program counts n-bit binary numbers without consecutive 1s using dynamic programming −
#include <stdio.h>
int countBinaryNumbers(int n) {
if (n == 1) return 2; // "0" and "1"
int endWithZero[n], endWithOne[n];
// Base case: 1-bit numbers
endWithZero[0] = 1; // "0"
endWithOne[0] = 1; // "1"
// Fill the arrays for 2 to n bits
for (int i = 1; i < n; i++) {
endWithZero[i] = endWithZero[i-1] + endWithOne[i-1];
endWithOne[i] = endWithZero[i-1];
}
return endWithZero[n-1] + endWithOne[n-1];
}
int main() {
int n = 4;
printf("For %d-bit binary numbers:<br>", n);
printf("Count of numbers without consecutive 1s: %d<br>", countBinaryNumbers(n));
// Test with different values
for (int i = 1; i <= 5; i++) {
printf("n=%d: %d<br>", i, countBinaryNumbers(i));
}
return 0;
}
For 4-bit binary numbers: Count of numbers without consecutive 1s: 8 n=1: 2 n=2: 3 n=3: 5 n=4: 8 n=5: 13
How It Works
The algorithm builds up the solution by tracking valid binary strings ending with 0 and 1 separately. For each bit position, it calculates how many valid strings of that length exist.
Time and Space Complexity
- Time Complexity: O(n) − single loop from 1 to n-1
- Space Complexity: O(n) − two arrays of size n
Key Points
- The sequence follows Fibonacci pattern: 2, 3, 5, 8, 13...
- Numbers ending with 0 can be followed by either 0 or 1
- Numbers ending with 1 can only be followed by 0 (to avoid consecutive 1s)
Conclusion
This dynamic programming solution efficiently counts n-bit binary numbers without consecutive 1s by tracking valid strings ending with 0 and 1 separately. The algorithm runs in O(n) time and produces results following the Fibonacci sequence.
