Count number of binary strings without consecutive 1's
Last Updated :
23 Jul, 2025
Given a positive integer n, the task is to count all possible distinct binary strings of length n such that there are no consecutive 1's.
Examples:
Input: n = 3
Output: 5
Explanation: 5 strings are ("000", "001", "010", "100", "101").
Input: n = 2
Output: 3
Explanation: 3 strings are ("00", "01", "10").
Using Recursion - O(2^n) Time and O(n) Space
The idea is to explore two possible choices at each step of building the binary string. When constructing a string of length n, at each index, we have two choices: either place a 0 or place a 1. If we choose to place a 0, we can proceed to the next index. However, if we choose to place a 1, we must ensure that the next index does not contain a 1, so we skip the next index.
Mathematically the recurrence relation will look like the following:
countStrings(i) = countStrings(i+1) + countStrings(i+2)
Base Case:
- countStrings(i) = 1, if i >= n.
C++
// C++ program to count number of binary
// strings without consecutive 1's using recursion
#include <bits/stdc++.h>
using namespace std;
int countRecur(int i, int n) {
// Base case
if (i >= n) return 1;
// If we take 1 at ith index,
// we cannot have 1 at (i-1)
int take = countRecur(i+2, n);
// If we skip 1, we can consider
// 1 at i-1.
int noTake = countRecur(i+1, n);
return take + noTake;
}
int countStrings(int n) {
return countRecur(0, n);
}
int main() {
int n = 3;
cout << countStrings(n);
return 0;
}
Java
// Java program to count number of binary
// strings without consecutive 1's using recursion
class GfG {
static int countRecur(int i, int n) {
// Base case
if (i >= n) return 1;
// If we take 1 at ith index,
// we cannot have 1 at (i-1)
int take = countRecur(i + 2, n);
// If we skip 1, we can consider
// 1 at i-1.
int noTake = countRecur(i + 1, n);
return take + noTake;
}
static int countStrings(int n) {
return countRecur(0, n);
}
public static void main(String[] args) {
int n = 3;
System.out.println(countStrings(n));
}
}
Python
# Python program to count number of binary
# strings without consecutive 1's using recursion
def countRecur(i, n):
# Base case
if i >= n:
return 1
# If we take 1 at ith index,
# we cannot have 1 at (i-1)
take = countRecur(i + 2, n)
# If we skip 1, we can consider
# 1 at i-1.
noTake = countRecur(i + 1, n)
return take + noTake
def countStrings(n):
return countRecur(0, n)
if __name__ == "__main__":
n = 3
print(countStrings(n))
C#
// C# program to count number of binary
// strings without consecutive 1's using recursion
using System;
class GfG {
static int countRecur(int i, int n) {
// Base case
if (i >= n) return 1;
// If we take 1 at ith index,
// we cannot have 1 at (i-1)
int take = countRecur(i + 2, n);
// If we skip 1, we can consider
// 1 at i-1.
int noTake = countRecur(i + 1, n);
return take + noTake;
}
static int countStrings(int n) {
return countRecur(0, n);
}
static void Main(string[] args) {
int n = 3;
Console.WriteLine(countStrings(n));
}
}
JavaScript
// JavaScript program to count number of binary
// strings without consecutive 1's using recursion
function countRecur(i, n) {
// Base case
if (i >= n) return 1;
// If we take 1 at ith index,
// we cannot have 1 at (i-1)
let take = countRecur(i + 2, n);
// If we skip 1, we can consider
// 1 at i-1.
let noTake = countRecur(i + 1, n);
return take + noTake;
}
function countStrings(n) {
return countRecur(0, n);
}
const n = 3;
console.log(countStrings(n));
Using Top-Down DP (Memoization) - O(n) Time and O(n) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure: Number of ways to make binary string at i'th index depends on the optimal solutions of countStrings(i+1) and countStrings(i+2). By combining these substructures, we can efficiently calculate number of ways to make binary strings with consecutive 1's at index i.
2. Overlapping Subproblems: While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times. For example, while calculating countStrings(3), countStrings(4) and countStrings(5) are called. countStrings(4) will again call countStrings(5) which will lead to Overlapping Subproblems.
- There is only one parameter: i that changes in the recursive solution. So we create a 1D array of size n for memoization.
- We initialize this array as -1 to indicate nothing is computed initially.
- Now we modify our recursive solution to first check if the value is -1, then only make recursive calls. This way, we avoid re-computations of the same subproblems.
C++
// C++ program to count number of binary
// strings without consecutive 1's using memoization
#include <bits/stdc++.h>
using namespace std;
int countRecur(int i, int n, vector<int> &memo) {
// Base case
if (i >= n) return 1;
// If value is memoized
if (memo[i]!=-1) return memo[i];
// If we take 1 at ith index,
// we cannot have 1 at (i-1)
int take = countRecur(i+2, n, memo);
// If we skip 1, we can consider
// 1 at i-1.
int noTake = countRecur(i+1, n, memo);
return memo[i] = take + noTake;
}
int countStrings(int n) {
vector<int> memo(n, -1);
return countRecur(0, n, memo);
}
int main() {
int n = 3;
cout << countStrings(n);
return 0;
}
Java
// Java program to count number of binary
// strings without consecutive 1's using memoization
class GfG {
static int countRecur(int i, int n, int[] memo) {
// Base case
if (i >= n) return 1;
// If value is memoized
if (memo[i] != -1) return memo[i];
// If we take 1 at ith index,
// we cannot have 1 at (i-1)
int take = countRecur(i + 2, n, memo);
// If we skip 1, we can consider
// 1 at i-1.
int noTake = countRecur(i + 1, n, memo);
return memo[i] = take + noTake;
}
static int countStrings(int n) {
int[] memo = new int[n];
for (int j = 0; j < n; j++) memo[j] = -1;
return countRecur(0, n, memo);
}
public static void main(String[] args) {
int n = 3;
System.out.println(countStrings(n));
}
}
Python
# Python program to count number of binary
# strings without consecutive 1's using memoization
def countRecur(i, n, memo):
# Base case
if i >= n:
return 1
# If value is memoized
if memo[i] != -1:
return memo[i]
# If we take 1 at ith index,
# we cannot have 1 at (i-1)
take = countRecur(i + 2, n, memo)
# If we skip 1, we can consider
# 1 at i-1.
noTake = countRecur(i + 1, n, memo)
memo[i] = take + noTake
return memo[i]
def countStrings(n):
memo = [-1] * n
return countRecur(0, n, memo)
if __name__ == "__main__":
n = 3
print(countStrings(n))
C#
// C# program to count number of binary
// strings without consecutive 1's using memoization
using System;
class GfG {
static int countRecur(int i, int n, int[] memo) {
// Base case
if (i >= n) return 1;
// If value is memoized
if (memo[i] != -1) return memo[i];
// If we take 1 at ith index,
// we cannot have 1 at (i-1)
int take = countRecur(i + 2, n, memo);
// If we skip 1, we can consider
// 1 at i-1.
int noTake = countRecur(i + 1, n, memo);
return memo[i] = take + noTake;
}
static int countStrings(int n) {
int[] memo = new int[n];
for (int j = 0; j < n; j++) memo[j] = -1;
return countRecur(0, n, memo);
}
static void Main(string[] args) {
int n = 3;
Console.WriteLine(countStrings(n));
}
}
JavaScript
// JavaScript program to count number of binary
// strings without consecutive 1's using memoization
function countRecur(i, n, memo) {
// Base case
if (i >= n) return 1;
// If value is memoized
if (memo[i] !== -1) return memo[i];
// If we take 1 at ith index,
// we cannot have 1 at (i-1)
let take = countRecur(i + 2, n, memo);
// If we skip 1, we can consider
// 1 at i-1.
let noTake = countRecur(i + 1, n, memo);
return memo[i] = take + noTake;
}
function countStrings(n) {
let memo = Array(n).fill(-1);
return countRecur(0, n, memo);
}
const n = 3;
console.log(countStrings(n));
Using Bottom-Up DP (Tabulation) - O(n) Time and O(n) Space
The idea is to fill the DP table based on next values. For each index, we can either place 1 or 0. The array is filled in an iterative manner from i = n-1 to i = 0.
The dynamic programming relation is as follows:
- dp[i] = dp[i+1] + dp[i+2]
C++
// C++ program to count number of binary
// strings without consecutive 1's using tabulation
#include <bits/stdc++.h>
using namespace std;
int countStrings(int n) {
if (n == 1)
return 2;
if (n == 2)
return 3;
vector<int> dp(n);
dp[n - 1] = 2;
dp[n - 2] = 3;
for (int i = n - 3; i >= 0; i--) {
dp[i] = dp[i + 1] + dp[i + 2];
}
return dp[0];
}
int main() {
int n = 3;
cout << countStrings(n);
return 0;
}
Java
// Java program to count number of binary
// strings without consecutive 1's using tabulation
class GfG {
static int countStrings(int n) {
if (n == 1) return 2;
if (n == 2) return 3;
int[] dp = new int[n];
dp[n - 1] = 2;
dp[n - 2] = 3;
for (int i = n - 3; i >= 0; i--) {
dp[i] = dp[i + 1] + dp[i + 2];
}
return dp[0];
}
public static void main(String[] args) {
int n = 3;
System.out.println(countStrings(n));
}
}
Python
# Python program to count number of binary
# strings without consecutive 1's using tabulation
def countStrings(n):
if n == 1:
return 2
if n == 2:
return 3
dp = [0] * n
dp[n - 1] = 2
dp[n - 2] = 3
for i in range(n - 3, -1, -1):
dp[i] = dp[i + 1] + dp[i + 2]
return dp[0]
if __name__ == "__main__":
n = 3
print(countStrings(n))
C#
// C# program to count number of binary
// strings without consecutive 1's using tabulation
using System;
class GfG {
static int countStrings(int n) {
if (n == 1) return 2;
if (n == 2) return 3;
int[] dp = new int[n];
dp[n - 1] = 2;
dp[n - 2] = 3;
for (int i = n - 3; i >= 0; i--) {
dp[i] = dp[i + 1] + dp[i + 2];
}
return dp[0];
}
static void Main(string[] args) {
int n = 3;
Console.WriteLine(countStrings(n));
}
}
JavaScript
// JavaScript program to count number of binary
// strings without consecutive 1's using tabulation
function countStrings(n) {
if (n === 1) return 2;
if (n === 2) return 3;
const dp = new Array(n).fill(0);
dp[n - 1] = 2;
dp[n - 2] = 3;
for (let i = n - 3; i >= 0; i--) {
dp[i] = dp[i + 1] + dp[i + 2];
}
return dp[0];
}
const n = 3;
console.log(countStrings(n));
Using Space Optimized DP - O(n) Time and O(1) Space
In previous approach of dynamic programming we have derive the relation between states as given below:
- dp[i] = dp[i+1] + dp[i+2]
We observe that for calculating dp[i] state we only need dp[i+1] and dp[i+2]. There is no need to store all the next states.
C++
// C++ program to count number of binary
// strings without consecutive 1's
// using space optimised dp
#include <bits/stdc++.h>
using namespace std;
int countStrings(int n) {
if (n == 1)
return 2;
if (n == 2)
return 3;
int prev1 = 3, prev2 = 2;
for (int i = n - 3; i >= 0; i--) {
int curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
int main() {
int n = 3;
cout << countStrings(n);
return 0;
}
Java
// Java program to count number of binary
// strings without consecutive 1's
// using space optimised dp
class GfG {
static int countStrings(int n) {
if (n == 1)
return 2;
if (n == 2)
return 3;
int prev1 = 3, prev2 = 2;
for (int i = n - 3; i >= 0; i--) {
int curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
public static void main(String[] args) {
int n = 3;
System.out.println(countStrings(n));
}
}
Python
# Python program to count number of binary
# strings without consecutive 1's
# using space optimised dp
def countStrings(n):
if n == 1:
return 2
if n == 2:
return 3
prev1, prev2 = 3, 2
for i in range(n - 3, -1, -1):
curr = prev1 + prev2
prev2 = prev1
prev1 = curr
return prev1
if __name__ == "__main__":
n = 3
print(countStrings(n))
C#
// C# program to count number of binary
// strings without consecutive 1's
// using space optimised dp
using System;
class GfG {
static int countStrings(int n) {
if (n == 1)
return 2;
if (n == 2)
return 3;
int prev1 = 3, prev2 = 2;
for (int i = n - 3; i >= 0; i--) {
int curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
static void Main(string[] args) {
int n = 3;
Console.WriteLine(countStrings(n));
}
}
JavaScript
// JavaScript program to count number of binary
// strings without consecutive 1's
// using space optimised dp
function countStrings(n) {
if (n === 1)
return 2;
if (n === 2)
return 3;
let prev1 = 3, prev2 = 2;
for (let i = n - 3; i >= 0; i--) {
let curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
const n = 3;
console.log(countStrings(n));
Using Matrix Exponentiation - O(logn) Time and O(logn) Space
The recurrence relation to count binary strings of length i is:
with bases cases F(1) = 2 and F(2) = 3.
Matrix exponentiation can be used to solve this problem in O(logn) time. Refer to Matrix Exponentiation for detailed approach.
C++
// C++ program to count number of binary
// strings without consecutive 1's
#include <bits/stdc++.h>
using namespace std;
// Function to mutiply two matrices
vector<vector<int>> multiply(vector<vector<int>>& v1, vector<vector<int>>& v2) {
vector<vector<int>> ans(2, vector<int>(2, 0));
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
ans[i][j] += v1[i][k] * v2[k][j];
}
}
}
return ans;
}
// Function to find matrix to the power n.
vector<vector<int>> power(vector<vector<int>> &v, int n) {
if (n == 0) {
return {{1, 0}, {0, 1}};
}
vector<vector<int>> res = power(v, n / 2);
res = multiply(res, res);
if (n % 2 == 1)
res = multiply(res, v);
return res;
}
int countStrings(int n) {
if (n == 2)
return 3;
if (n == 1)
return 2;
vector<vector<int>> v = {{1, 1}, {1, 0}};
vector<vector<int>> p = power(v, n - 2);
int ans = p[0][0] * 3 + p[0][1] * 2;
return ans;
}
int main() {
int n = 3;
cout << countStrings(n);
return 0;
}
Java
// Java program to count number of binary
// strings without consecutive 1's
class GfG {
// Function to multiply two matrices
static int[][] multiply(int[][] v1, int[][] v2) {
int[][] ans = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
ans[i][j] += v1[i][k] * v2[k][j];
}
}
}
return ans;
}
// Function to find matrix to the power n
static int[][] power(int[][] v, int n) {
if (n == 0) {
return new int[][] { { 1, 0 }, { 0, 1 } };
}
int[][] res = power(v, n / 2);
res = multiply(res, res);
if (n % 2 == 1) {
res = multiply(res, v);
}
return res;
}
static int countStrings(int n) {
if (n == 2)
return 3;
if (n == 1)
return 2;
int[][] v = { { 1, 1 }, { 1, 0 } };
int[][] p = power(v, n - 2);
int ans = p[0][0] * 3 + p[0][1] * 2;
return ans;
}
public static void main(String[] args) {
int n = 3;
System.out.println(countStrings(n));
}
}
Python
# Python program to count number of binary
# strings without consecutive 1's
# Function to multiply two matrices
def multiply(v1, v2):
ans = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
for k in range(2):
ans[i][j] += v1[i][k] * v2[k][j]
return ans
# Function to find matrix to the power n
def power(v, n):
if n == 0:
return [[1, 0], [0, 1]]
res = power(v, n // 2)
res = multiply(res, res)
if n % 2 == 1:
res = multiply(res, v)
return res
def countStrings(n):
if n == 2:
return 3
if n == 1:
return 2
v = [[1, 1], [1, 0]]
p = power(v, n - 2)
ans = p[0][0] * 3 + p[0][1] * 2
return ans
if __name__ == "__main__":
n = 3
print(countStrings(n))
C#
// C# program to count number of binary
// strings without consecutive 1's
using System;
class GfG {
// Function to multiply two matrices
static int[, ] multiply(int[, ] v1, int[, ] v2) {
int[, ] ans = new int[2, 2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
ans[i, j] += v1[i, k] * v2[k, j];
}
}
}
return ans;
}
// Function to find matrix to the power n
static int[, ] power(int[, ] v, int n) {
if (n == 0) {
return new int[, ] { { 1, 0 }, { 0, 1 } };
}
int[, ] res = power(v, n / 2);
res = multiply(res, res);
if (n % 2 == 1) {
res = multiply(res, v);
}
return res;
}
static int countStrings(int n) {
if (n == 2)
return 3;
if (n == 1)
return 2;
int[, ] v = { { 1, 1 }, { 1, 0 } };
int[, ] p = power(v, n - 2);
int ans = p[0, 0] * 3 + p[0, 1] * 2;
return ans;
}
static void Main(string[] args) {
int n = 3;
Console.WriteLine(countStrings(n));
}
}
JavaScript
// JavaScript program to count number of binary
// strings without consecutive 1's
// Function to multiply two matrices
function multiply(v1, v2) {
let ans = [ [ 0, 0 ], [ 0, 0 ] ];
for (let i = 0; i < 2; i++) {
for (let j = 0; j < 2; j++) {
for (let k = 0; k < 2; k++) {
ans[i][j] += v1[i][k] * v2[k][j];
}
}
}
return ans;
}
// Function to find matrix to the power n
function power(v, n) {
if (n === 0) {
return [ [ 1, 0 ], [ 0, 1 ] ];
}
let res = power(v, Math.floor(n / 2));
res = multiply(res, res);
if (n % 2 === 1) {
res = multiply(res, v);
}
return res;
}
function countStrings(n) {
if (n === 2)
return 3;
if (n === 1)
return 2;
let v = [ [ 1, 1 ], [ 1, 0 ] ];
let p = power(v, n - 2);
let ans = p[0][0] * 3 + p[0][1] * 2;
return ans;
}
const n = 3;
console.log(countStrings(n));
Related article:
Count Binary Strings With No Consecutive 1s | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem