Java Program to Count number of binary strings without consecutive 1's
Last Updated :
10 Nov, 2023
Write a Java program for a given positive integer N, the task is to count all possible distinct binary strings of length N such that there are no consecutive 1s.
Examples:
Input: N = 2
Output: 3
// The 3 strings are 00, 01, 10
Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101
Java Program to Count a number of binary strings without consecutive 1's using Dynamic Programming:
Let a[i] be the number of binary strings of length i that do not contain any two consecutive 1s and which end in 0. Similarly, let b[i] be the number of such strings which end in 1. We can append either 0 or 1 to a string ending in 0, but we can only append 0 to a string ending in 1. This yields the recurrence relation:
a[i] = a[i - 1] + b[i - 1]
b[i] = a[i - 1]
The base cases of above recurrence are a[1] = b[1] = 1. The total number of strings of length i is just a[i] + b[i].
Below is the implementation of the above approach:
Java
import java.io.*;
class Subset_sum
{
static int countStrings(int n)
{
int a[] = new int [n];
int b[] = new int [n];
a[0] = b[0] = 1;
for (int i = 1; i < n; i++)
{
a[i] = a[i-1] + b[i-1];
b[i] = a[i-1];
}
return (a[n-1] + b[n-1])%1000000007;
}
/* Driver program to test above function */
public static void main (String args[])
{
System.out.println(countStrings(3));
}
}/* This code is contributed by Rajat Mishra */
Time Complexity: O(N)
Auxiliary Space: O(N)
Another method:
From the above method it is clear that we only want just previous value in the for loop which we can also do by replacing the array with the variable.
Below is the implementation of the above approach:
Java
import java.io.*;
class Subset_sum {
static int countStrings(int n)
{
int a = 1;
int b = 1;
for (int i = 1; i < n; i++) {
// Here we have used the temp variable because
// we want to assign the older value of a to b
int temp = a + b;
b = a;
a = temp;
}
return (a + b)%1000000007;
}
/* Driver program to test above function */
public static void main(String args[])
{
System.out.println(countStrings(3));
}
}
// This code is contributed by Aditya Kumar (adityakumar129)
Time Complexity: O(N)
Auxiliary Space: O(1)
Fibonacci in Log (n) without using Matrix Exponentiation:
As for calculating the n we can express it as the product of n/2 and n/2 ((n/2+1) for n is odd) as they are independent ,now as there are the cases when we combining these two half values to get full length there may be occurrence of consecutive 1’s at the joining. So we have to subtract those cases to get the final result.
f(n)=f(n/2)*f(n/2) - (those values which has consecutive 1's at the joining part)
Below is the implementation of the above approach:
Java
import java.util.*;
class Solution {
// Storing the pre-calculated value
// using a HashMap for DP
Map<Long, Long> mp = new HashMap<>();
long countStrings(long N) {
// Base cases
if (N == 0) return 1;
if (N == 1) return 2;
if (N == 2) return 3;
long mod = (long)1e9 + 7;
// Check if the value is already present in the map
if (mp.containsKey(N)) {
return mp.get(N);
}
// Recursive calls and memoization
long a = mp.getOrDefault(N/2 - 1, countStrings(N/2 - 1)) % mod;
long b = mp.getOrDefault(N/2, countStrings(N/2)) % mod;
long c = mp.getOrDefault(N/2 + 1, countStrings(N/2 + 1)) % mod;
// Calculations
long result;
if (N % 2 == 1)
result = ((b * c % mod) - ((c - b) * (b - a) % mod) + mod) % mod;
else
result = ((b * b % mod) - ((b - a) * (b - a) % mod) + mod) % mod;
// Store the result in the map for future use
mp.put(N, result);
return result;
}
}
public class Main {
public static void main(String[] args) {
long N = 10;
Solution obj = new Solution();
System.out.println(obj.countStrings(N));
}
}
Time Complexity: O(log N)
Auxiliary Space: O(log N)
Please refer complete article on Count number of binary strings without consecutive 1’s for more details!
Similar Reads
Java Program to Count set bits in an integer Write an efficient program to count number of 1s in binary representation of an integer. Examples :Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bitsInput : n = 13Output : 3Binary representation of 11 is 1101 and has 3 set bits1. Simple Method Loop through all bits in an int
2 min read
Java Program to Convert a Decimal Number to Binary & Count the Number of 1s As per the number system, default computations are carried over decimal numbers whose base is standardized as 10. Machine computes all the execution at the physical layer in 0s and 1s. So arises a need for a number system with base 2 known as a binary number system. A binary number can be converted
4 min read
Java Program to Count 1's in a sorted binary array Given a binary array sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = {1, 1, 0, 0, 0, 0, 0} Output: 2 Input: arr[] = {1, 1, 1, 1, 1, 1, 1} Output: 7 Input: arr[] = {0, 0, 0, 0, 0, 0, 0} Output: 0 A simple solution is to linearly traverse the array. The time c
3 min read
Find the number of binary strings of length N with at least 3 consecutive 1s Given an integer N. The task is to find the number of all possible distinct binary strings of length N which have at least 3 consecutive 1s.Examples: Input: N = 3 Output: 1 The only string of length 3 possible is "111".Input: N = 4 Output: 3 The 3 strings are "1110", "0111" and "1111". Naive approac
9 min read
Find the number of binary strings of length N with at least 3 consecutive 1s Given an integer N. The task is to find the number of all possible distinct binary strings of length N which have at least 3 consecutive 1s.Examples: Input: N = 3 Output: 1 The only string of length 3 possible is "111".Input: N = 4 Output: 3 The 3 strings are "1110", "0111" and "1111". Naive approac
9 min read
Find all the patterns of "1(0+)1" in a given string (General Approach) A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0's. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern.
5 min read