# Find the number of binary strings of length N with at least 3 consecutive 1s in C++

C++Server Side ProgrammingProgramming

Suppose, we have an integer N, We have to find the number of all possible distinct binary strings of the length N, which have at least three consecutive 1s. So if n = 4, then the numbers will be 0111, 1110, 1111, so output will be 3.

To solve this, we can use the Dynamic programming approach. So DP(i, x) indicates number of strings of length i with x consecutive 1s in position i + 1 to i + x. Then the recurrence relation will be like −

DP(i, x) = DP(i – 1, 0) + DP(i – 1, x + 1).

The recurrence is based on the fact, that either the string can have 0 or 1 present at position i.

• If it has 0, at ith index then for (i – 1)th position value of x = 0
• If it has 1, at ith index then for (i – 1)th position value of x = 1 + value of x at position i

## Example

Live Demo

#include<iostream>
using namespace std;
int n;
int numberCount(int i, int x, int table[]) {
if (i < 0)
return x == 3;
if (table[i][x] != -1)
return table[i][x];
table[i][x] = numberCount(i - 1, 0, table);
table[i][x] += numberCount(i - 1, x + 1, table);
return table[i][x];
}
int main() {
n = 4;
int table[n];
for (int i = 0; i < n; i++)
for (int j = 0; j < 4; j++)
table[i][j] = -1;
for (int i = 0; i < n; i++) {
table[i] = (1 << (i + 1));
}
cout << "The number of binary strings with at least 3 consecutive 1s: " << numberCount(n - 1, 0, table);
}

## Output

The number of binary strings with at least 3 consecutive 1s: 3