- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

#include<iostream> using namespace std; int n; int numberCount(int i, int x, int table[][4]) { 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][4]; 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][3] = (1 << (i + 1)); } cout << "The number of binary strings with at least 3 consecutive 1s: " << numberCount(n - 1, 0, table); }

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

- Related Questions & Answers
- Find consecutive 1s of length >= n in binary representation of a number in C++
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Find the number of consecutive zero at the end after multiplying n numbers in Python
- Find row number of a binary matrix having maximum number of 1s in C++
- Count number of binary strings without consecutive 1's in C
- Python – Find the sum of Length of Strings at given indices
- Program to find length of longest substring with character count of at least k in Python
- Bitwise AND of N binary strings in C++
- Bitwise OR of N binary strings in C++
- Find perimeter of shapes formed with 1s in binary matrix in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
- Counting the number of 1s upto n in JavaScript
- C/C++ Program to Count number of binary strings without consecutive 1’s?
- Python Program to Extract Strings with at least given number of characters from other list
- Program to Count number of binary strings without consecutive 1’s in C/C++?

Advertisements