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
PHP Program to Count Number of Binary Strings without Consecutive 1’s
In PHP, counting binary strings without consecutive 1's is a classic dynamic programming problem. A binary string contains only 0's and 1's, and we need to count valid strings where no two 1's appear next to each other.
Understanding the Problem
Let's analyze binary strings of length 3 to understand the pattern
All possible binary strings of length 3: 000, 001, 010, 011, 100, 101, 110, 111
Valid strings (without consecutive 1's): 000, 001, 010, 100
Invalid strings (with consecutive 1's): 011, 110, 111
So for length 3, we have 5 valid binary strings without consecutive 1's.
Method 1: Using Dynamic Programming
This approach uses the Fibonacci pattern where dp[i] = dp[i-1] + dp[i-2] ?
<?php
function countBinaryStrings($n) {
if ($n == 0) return 1;
if ($n == 1) return 2;
$dp = array();
$dp[0] = 1; // Empty string
$dp[1] = 2; // "0", "1"
for ($i = 2; $i <= $n; $i++) {
$dp[$i] = $dp[$i - 1] + $dp[$i - 2];
}
return $dp[$n];
}
$n = 5;
$count = countBinaryStrings($n);
echo "Number of binary strings of length $n without consecutive 1's: " . $count;
?>
Number of binary strings of length 5 without consecutive 1's: 13
Method 2: State-based Dynamic Programming
This method tracks strings ending with 0 and strings ending with 1 separately ?
<?php
function countStrings($n) {
if ($n == 0) return 1;
// a[i] = count of strings ending with 0
// b[i] = count of strings ending with 1
$a = array_fill(0, $n, 0);
$b = array_fill(0, $n, 0);
$a[0] = 1; // "0"
$b[0] = 1; // "1"
for ($i = 1; $i < $n; $i++) {
$a[$i] = $a[$i - 1] + $b[$i - 1]; // Can append 0 after both 0 and 1
$b[$i] = $a[$i - 1]; // Can append 1 only after 0
}
return $a[$n - 1] + $b[$n - 1];
}
$n = 5;
echo "Number of binary strings of length $n without consecutive 1's: " . countStrings($n);
?>
Number of binary strings of length 5 without consecutive 1's: 13
Pattern Analysis
| Length (n) | Count | Sequence |
|---|---|---|
| 1 | 2 | 0, 1 |
| 2 | 3 | 00, 01, 10 |
| 3 | 5 | 000, 001, 010, 100, 101 |
| 4 | 8 | Fibonacci pattern: 2, 3, 5, 8... |
Conclusion
Both methods solve the problem using dynamic programming principles. Method 1 follows the Fibonacci sequence pattern, while Method 2 uses state-based tracking. The result follows the Fibonacci sequence starting with 2, 3, 5, 8, 13... for lengths 1, 2, 3, 4, 5 respectively.
