Count binary strings of length N with no consecutive zeros

Updated

Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 0’s.

Examples :

Input : N = 2
Output : 3
Explanation :
01,10,11 are binary strings of length 2 without consecutive 0’s

Input : N = 3
Output : 5
Explanation :
010, 011, 101, 110, 111 are binary strings of length 3 without
consecutive 0’s

Approach :

If we take a closer look at the pattern, we can observe that the count is actually (n+2)’th Fibonacci number for n >= 1. 2, 3, 5, 8, 13, 21, 34, 55……………………

Implementation :

#include<bits/stdc++.h>
using namespace std;
 
int fib(int n) { 
  double phi = (1 + sqrt(5)) / 2; 
  return round(pow(phi, n) / sqrt(5)); 
}
 
int main() 
{
    int n = 4;
    cout<<fib(n+2);  //(n+2)th fibonacci number
    return 0;
}

Output :

8
Comment
Next tutorial
Mithlesh Upadhyay Published 1 Dec 2026 · 1 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials