Number of Binary Strings of length N with K adjacent Set Bits
Last Updated :
05 May, 2025
Given n and k . The task is to find the number of binary strings of length n out of 2n such that they satisfy f(bit string) = k.
Where,
f(x) = Number of times a set bit is adjacent to
another set bit in a binary string x.
For Example:
f(011101101) = 3
f(010100000) = 0
f(111111111) = 8
Examples:
Input : n = 5, k = 2
Output : 6
Explanation
There are 6 ways to form bit strings of length 5
such that f(bit string s) = 2,
These possible strings are:-
00111, 01110, 10111, 11011, 11100, 11101
Method 1 (Brute Force):
The simplest approach is to solve the problem recursively, by passing the current index, the value of f(bit string) formed till current index and the last bit we placed in the binary string formed till (current index - 1). If we reach the index where current index = n and the value of f(bit string) = k then we count this way else we dont.
Below is the implementation of the brute force approach:
C++
// C++ program to find the number of Bit Strings
// of length N with K adjacent set bits
#include <bits/stdc++.h>
using namespace std;
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
int waysToKAdjacentSetBits(int n, int k, int currentIndex,
int adjacentSetBits, int lastBit)
{
/* Base Case when we form bit string of length n */
if (currentIndex == n) {
// if f(bit string) = k, count this way
if (adjacentSetBits == k)
return 1;
return 0;
}
int noOfWays = 0;
/* Check if the last bit was set,
if it was set then call for
next index by incrementing the
adjacent bit count else just call
the next index with same value of
adjacent bit count and either set the
bit at current index or let it remain
unset */
if (lastBit == 1) {
// set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits + 1, 1);
// unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k,currentIndex + 1,
adjacentSetBits, 0);
}
else if (!lastBit) {
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 0);
}
return noOfWays;
}
// Driver Code
int main()
{
int n = 5, k = 2;
/* total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) */
int totalWays = waysToKAdjacentSetBits(n, k, 1, 0, 1)
+ waysToKAdjacentSetBits(n, k, 1, 0, 0);
cout << "Number of ways = " << totalWays << "\n";
return 0;
}
Java
// Java program to find the number of Bit Strings
// of length N with K adjacent set bits
import java.util.*;
class solution
{
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
static int waysToKAdjacentSetBits(int n, int k, int currentIndex,
int adjacentSetBits, int lastBit)
{
// Base Case when we form bit string of length n
if (currentIndex == n) {
// if f(bit string) = k, count this way
if (adjacentSetBits == k)
return 1;
return 0;
}
int noOfWays = 0;
/* Check if the last bit was set,
if it was set then call for
next index by incrementing the
adjacent bit count else just call
the next index with same value of
adjacent bit count and either set the
bit at current index or let it remain
unset */
if (lastBit == 1) {
// set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits + 1, 1);
// unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k,currentIndex + 1,
adjacentSetBits, 0);
}
else if (lastBit == 0) {
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 0);
}
return noOfWays;
}
// Driver Code
public static void main(String args[])
{
int n = 5, k = 2;
/* total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) */
int totalWays = waysToKAdjacentSetBits(n, k, 1, 0, 1)
+ waysToKAdjacentSetBits(n, k, 1, 0, 0);
System.out.println("Number of ways = "+totalWays);
}
}
//This code is contributed by
// Surendra _Gangwar
Python
# Python 3 program to find the number of Bit
# Strings of length N with K adjacent set bits
# Function to find the number of Bit Strings
# of length N with K adjacent set bits
def waysToKAdjacentSetBits(n, k, currentIndex,
adjacentSetBits, lastBit):
# Base Case when we form bit string of length n
if (currentIndex == n):
# if f(bit string) = k, count this way
if (adjacentSetBits == k):
return 1;
return 0
noOfWays = 0
# Check if the last bit was set, if it was set
# then call for next index by incrementing the
# adjacent bit count else just call the next
# index with same value of adjacent bit count
# and either set the bit at current index or
# let it remain unset
if (lastBit == 1):
# set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits + 1, 1);
# unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k,currentIndex + 1,
adjacentSetBits, 0);
elif (lastBit != 1):
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 0);
return noOfWays;
# Driver Code
n = 5; k = 2;
# total ways = (ways by placing 1st bit as 1 +
# ways by placing 1st bit as 0)
totalWays = (waysToKAdjacentSetBits(n, k, 1, 0, 1) +
waysToKAdjacentSetBits(n, k, 1, 0, 0));
print("Number of ways =", totalWays);
# This code is contributed by Akanksha Rai
C#
// C# program to find the number of Bit Strings
// of length N with K adjacent set bits
using System;
class GFG
{
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
static int waysToKAdjacentSetBits(int n, int k, int currentIndex,
int adjacentSetBits, int lastBit)
{
/* Base Case when we form bit
string of length n */
if (currentIndex == n)
{
// if f(bit string) = k, count this way
if (adjacentSetBits == k)
return 1;
return 0;
}
int noOfWays = 0;
/* Check if the last bit was set, if it was
set then call for next index by incrementing
the adjacent bit count else just call the next
index with same value of adjacent bit count and
either set the bit at current index or let it
remain unset */
if (lastBit == 1)
{
// set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits + 1, 1);
// unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k,currentIndex + 1,
adjacentSetBits, 0);
}
else if (lastBit != 1)
{
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 0);
}
return noOfWays;
}
// Driver Code
public static void Main()
{
int n = 5, k = 2;
/* total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) */
int totalWays = waysToKAdjacentSetBits(n, k, 1, 0, 1) +
waysToKAdjacentSetBits(n, k, 1, 0, 0);
Console.WriteLine("Number of ways = " + totalWays);
}
}
// This code is contributed
// by Akanksha Rai
JavaScript
<script>
// Javascript program to find the number of Bit Strings
// of length N with K adjacent set bits
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
function waysToKAdjacentSetBits(n, k, currentIndex,
adjacentSetBits, lastBit)
{
/* Base Case when we form bit string of length n */
if (currentIndex == n) {
// if f(bit string) = k, count this way
if (adjacentSetBits == k)
return 1;
return 0;
}
let noOfWays = 0;
/* Check if the last bit was set,
if it was set then call for
next index by incrementing the
adjacent bit count else just call
the next index with same value of
adjacent bit count and either set the
bit at current index or let it remain
unset */
if (lastBit == 1) {
// set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits + 1, 1);
// unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(n, k,currentIndex + 1,
adjacentSetBits, 0);
}
else if (!lastBit) {
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(n, k, currentIndex + 1,
adjacentSetBits, 0);
}
return noOfWays;
}
// Driver Code
let n = 5, k = 2;
/* total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) */
let totalWays = waysToKAdjacentSetBits(n, k, 1, 0, 1)
+ waysToKAdjacentSetBits(n, k, 1, 0, 0);
document.write("Number of ways = " + totalWays);
</script>
PHP
<?php
// PHP program to find the number of
// Bit Strings of length N with K
// adjacent set bits
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
function waysToKAdjacentSetBits($n, $k, $currentIndex,
$adjacentSetBits, $lastBit)
{
/* Base Case when we form bit
string of length n */
if ($currentIndex == $n)
{
// if f(bit string) = k, count this way
if ($adjacentSetBits == $k)
return 1;
return 0;
}
$noOfWays = 0;
/* Check if the last bit was set, if it
was set then call for next index by
incrementing the adjacent bit count else
just call the next index with same value
of adjacent bit count and either set the
bit at current index or let it remain
unset */
if ($lastBit == 1)
{
// set the bit at currentIndex
$noOfWays += waysToKAdjacentSetBits($n, $k, $currentIndex + 1,
$adjacentSetBits + 1, 1);
// unset the bit at currentIndex
$noOfWays += waysToKAdjacentSetBits($n, $k,$currentIndex + 1,
$adjacentSetBits, 0);
}
else if (!$lastBit)
{
$noOfWays += waysToKAdjacentSetBits($n, $k, $currentIndex + 1,
$adjacentSetBits, 1);
$noOfWays += waysToKAdjacentSetBits($n, $k, $currentIndex + 1,
$adjacentSetBits, 0);
}
return $noOfWays;
}
// Driver Code
$n = 5;
$k = 2;
/* total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) */
$totalWays = waysToKAdjacentSetBits($n, $k, 1, 0, 1) +
waysToKAdjacentSetBits($n, $k, 1, 0, 0);
echo "Number of ways = ", $totalWays, "\n";
// This code is contributed by ajit
?>
Method 2 (efficient): In method 1, there are overlapping subproblems to remove for which we can apply Dynamic Programming (Memoization).
To optimize method 1, we can apply memoization to the above recursive solution such that,
DP[i][j][k] = Number of ways to form bit string of length i with
f(bit string till i) = j where the last bit is k,
which can be 0 or 1 depending on whether the
last bit was set or not
Below is the implementation of the efficient approach:
C++
// C++ program to find the number of Bit Strings
// of length N with K adjacent set bits
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
int waysToKAdjacentSetBits(int dp[][MAX][2], int n, int k,
int currentIndex, int adjacentSetBits, int lastBit)
{
/* Base Case when we form bit
string of length n */
if (currentIndex == n) {
// if f(bit string) = k, count this way
if (adjacentSetBits == k)
return 1;
return 0;
}
if (dp[currentIndex][adjacentSetBits][lastBit] != -1) {
return dp[currentIndex][adjacentSetBits][lastBit];
}
int noOfWays = 0;
/* Check if the last bit was set,
if it was set then call for
next index by incrementing the
adjacent bit count else just call
the next index with same value of
adjacent bit count and either set the
bit at current index or let it remain
unset */
if (lastBit == 1) {
// set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1,
adjacentSetBits + 1, 1);
// unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1,
adjacentSetBits, 0);
}
else if (!lastBit) {
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1,
adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1,
adjacentSetBits, 0);
}
dp[currentIndex][adjacentSetBits][lastBit] = noOfWays;
return noOfWays;
}
// Driver Code
int main()
{
int n = 5, k = 2;
/* dp[i][j][k] represents bit strings of length i
with f(bit string) = j and last bit as k */
int dp[MAX][MAX][2];
memset(dp, -1, sizeof(dp));
/* total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) */
int totalWays = waysToKAdjacentSetBits(dp, n, k, 1, 0, 1)
+ waysToKAdjacentSetBits(dp, n, k, 1, 0, 0);
cout << "Number of ways = " << totalWays << "\n";
return 0;
}
Java
// Java program to find the number of Bit Strings
// of length N with K adjacent set bits
class solution
{
static final int MAX=1000;
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
static int waysToKAdjacentSetBits(int dp[][][], int n, int k,
int currentIndex, int adjacentSetBits, int lastBit)
{
/* Base Case when we form bit
string of length n */
if (currentIndex == n) {
// if f(bit string) = k, count this way
if (adjacentSetBits == k)
return 1;
return 0;
}
if (dp[currentIndex][adjacentSetBits][lastBit] != -1) {
return dp[currentIndex][adjacentSetBits][lastBit];
}
int noOfWays = 0;
/* Check if the last bit was set,
if it was set then call for
next index by incrementing the
adjacent bit count else just call
the next index with same value of
adjacent bit count and either set the
bit at current index or let it remain
unset */
if (lastBit == 1) {
// set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1,
adjacentSetBits + 1, 1);
// unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1,
adjacentSetBits, 0);
}
else if (lastBit==0) {
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1,
adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1,
adjacentSetBits, 0);
}
dp[currentIndex][adjacentSetBits][lastBit] = noOfWays;
return noOfWays;
}
// Driver Code
public static void main(String args[])
{
int n = 5, k = 2;
/* dp[i][j][k] represents bit strings of length i
with f(bit string) = j and last bit as k */
int dp[][][]= new int[MAX][MAX][2];
//initialize the dp
for(int i=0;i<MAX;i++)
for(int j=0;j<MAX;j++)
for(int k1=0;k1<2;k1++)
dp[i][j][k1]=-1;
/* total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) */
int totalWays = waysToKAdjacentSetBits(dp, n, k, 1, 0, 1)
+ waysToKAdjacentSetBits(dp, n, k, 1, 0, 0);
System.out.print( "Number of ways = " + totalWays + "\n");
}
}
Python
# Python3 program to find the number of Bit Strings
# of length N with K adjacent set bits
MAX = 1000
# Function to find the number of Bit Strings
# of length N with K adjacent set bits
def waysToKAdjacentSetBits(dp, n, k, currentIndex, adjacentSetBits, lastBit):
""" Base Case when we form bit
string of length n """
if currentIndex == n:
# if f(bit string) = k, count this way
if adjacentSetBits == k:
return 1
return 0
if dp[currentIndex][adjacentSetBits][lastBit] != -1:
return dp[currentIndex][adjacentSetBits][lastBit]
noOfWays = 0
""" Check if the last bit was set,
if it was set then call for
next index by incrementing the
adjacent bit count else just call
the next index with same value of
adjacent bit count and either set the
bit at current index or let it remain
unset """
if lastBit == 1:
# set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1, adjacentSetBits + 1, 1)
# unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1, adjacentSetBits, 0)
elif not lastBit:
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1, adjacentSetBits, 1)
noOfWays += waysToKAdjacentSetBits(dp, n, k, currentIndex + 1, adjacentSetBits, 0)
dp[currentIndex][adjacentSetBits][lastBit] = noOfWays
return noOfWays
n, k = 5, 2
""" dp[i][j][k] represents bit strings of length i
with f(bit string) = j and last bit as k """
dp = [[[-1 for i in range(2)] for i in range(MAX)] for j in range(MAX)]
""" total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) """
totalWays = waysToKAdjacentSetBits(dp, n, k, 1, 0, 1) + waysToKAdjacentSetBits(dp, n, k, 1, 0, 0)
print( "Number of ways =", totalWays)
# This code is contributed by decode2207.
C#
using System;
// C# program to find the number
// of Bit Strings of length N
// with K adjacent set bits
class GFG
{
static readonly int MAX=1000;
// Function to find the number
// of Bit Strings of length N
// with K adjacent set bits
static int waysToKAdjacentSetBits(int [,,]dp,
int n, int k,
int currentIndex,
int adjacentSetBits,
int lastBit)
{
/* Base Case when we form bit
string of length n */
if (currentIndex == n)
{
// if f(bit string) = k, count this way
if (adjacentSetBits == k)
return 1;
return 0;
}
if (dp[currentIndex, adjacentSetBits,
lastBit] != -1)
{
return dp[currentIndex,
adjacentSetBits, lastBit];
}
int noOfWays = 0;
/* Check if the last bit was set,
if it was set then call for
next index by incrementing the
adjacent bit count else just call
the next index with same value of
adjacent bit count and either set the
bit at current index or let it remain
unset */
if (lastBit == 1)
{
// set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n,
k, currentIndex + 1,
adjacentSetBits + 1, 1);
// unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n,
k, currentIndex + 1,
adjacentSetBits, 0);
}
else if (lastBit==0)
{
noOfWays += waysToKAdjacentSetBits(dp,
n, k, currentIndex + 1,
adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(dp,
n, k, currentIndex + 1,
adjacentSetBits, 0);
}
dp[currentIndex,adjacentSetBits,lastBit] = noOfWays;
return noOfWays;
}
// Driver Code
public static void Main(String []args)
{
int n = 5, k = 2;
/* dp[i,j,k] represents bit strings
of length i with f(bit string) = j
and last bit as k */
int [,,]dp = new int[MAX, MAX, 2];
// initialize the dp
for(int i = 0; i < MAX; i++)
for(int j = 0; j < MAX; j++)
for(int k1 = 0; k1 < 2; k1++)
dp[i, j, k1]=-1;
/* total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) */
int totalWays = waysToKAdjacentSetBits(dp, n, k, 1, 0, 1)
+ waysToKAdjacentSetBits(dp, n, k, 1, 0, 0);
Console.Write( "Number of ways = " + totalWays + "\n");
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript program to find the number of Bit Strings
// of length N with K adjacent set bits
var MAX = 1000;
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
function waysToKAdjacentSetBits(dp, n, k,
currentIndex, adjacentSetBits, lastBit)
{
/* Base Case when we form bit
string of length n */
if (currentIndex == n) {
// if f(bit string) = k, count this way
if (adjacentSetBits == k)
return 1;
return 0;
}
if (dp[currentIndex][adjacentSetBits][lastBit] != -1) {
return dp[currentIndex][adjacentSetBits][lastBit];
}
var noOfWays = 0;
/* Check if the last bit was set,
if it was set then call for
next index by incrementing the
adjacent bit count else just call
the next index with same value of
adjacent bit count and either set the
bit at current index or let it remain
unset */
if (lastBit == 1) {
// set the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n, k,
currentIndex + 1, adjacentSetBits + 1, 1);
// unset the bit at currentIndex
noOfWays += waysToKAdjacentSetBits(dp, n, k,
currentIndex + 1, adjacentSetBits, 0);
}
else if (!lastBit) {
noOfWays += waysToKAdjacentSetBits(dp, n, k,
currentIndex + 1, adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(dp, n, k,
currentIndex + 1, adjacentSetBits, 0);
}
dp[currentIndex][adjacentSetBits][lastBit] = noOfWays;
return noOfWays;
}
// Driver Code
var n = 5, k = 2;
/* dp[i][j][k] represents bit strings of length i
with f(bit string) = j and last bit as k */
var dp = Array.from(Array(MAX), ()=>Array(MAX));
for(var i =0; i<MAX; i++)
for(var j =0; j<MAX; j++)
dp[i][j] = new Array(2).fill(-1);
/* total ways = (ways by placing 1st bit as 1 +
ways by placing 1st bit as 0) */
var totalWays = waysToKAdjacentSetBits(dp, n, k, 1, 0, 1)
+ waysToKAdjacentSetBits(dp, n, k, 1, 0, 0);
document.write( "Number of ways = " + totalWays + "<br>");
</script>
Efficient approach : Using DP Tabulation method ( Iterative approach )
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.
Steps to solve this problem :
- Create a DP to store the solution of the subproblems and initialize it with 0.
- Initializing the base case, when length of bit string is 1
dp[1][0][1] = 1;
dp[1][0][0] = 1; - Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP.
- Now create a variable totalWays where totalWays = dp[n][k][0] + dp[n][k][1].
- Return the final solution stored in totalWays.
Implementation :
C++
// C++ program to find the number of Bit Strings
// of length N with K adjacent set bits
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
int waysToKAdjacentSetBits(int n, int k) {
// dp[i][j][k] represents bit strings of length i
// with f(bit string) = j and last bit as k
int dp[MAX][MAX][2];
memset(dp, 0, sizeof(dp));
// Initializing the base case
// when length of bit string is 1
dp[1][0][1] = 1;
dp[1][0][0] = 1;
// Filling up the DP Table
for(int i = 2; i <= n; i++) {
for(int j = 0; j <= k; j++) {
dp[i][j][0] = dp[i-1][j][0] + dp[i-1][j][1];
if(j > 0) {
dp[i][j][1] = dp[i-1][j-1][0];
}
dp[i][j][1] += dp[i-1][j][1];
}
}
// Total number of ways
int totalWays = dp[n][k][0] + dp[n][k][1];
return totalWays;
}
// Driver Code
int main() {
int n = 5, k = 2;
int totalWays = waysToKAdjacentSetBits(n, k);
cout << "Number of ways = " << totalWays << "\n";
return 0;
}
Java
// Java program to find the number of Bit Strings
// of length N with K adjacent set bits
import java.util.Arrays;
public class Main {
static final int MAX = 1000;
// Function to find the number of Bit Strings
// of length N with K adjacent set bits
static int waysToKAdjacentSetBits(int n, int k) {
// dp[i][j][k] represents bit strings of length i
// with f(bit string) = j and last bit as k
int[][][] dp = new int[MAX][MAX][2];
for (int[][] array2D : dp) {
for (int[] array1D : array2D) {
Arrays.fill(array1D, 0);
}
}
// Initializing the base case
// when length of bit string is 1
dp[1][0][1] = 1;
dp[1][0][0] = 1;
// Filling up the DP Table
for (int i = 2; i <= n; i++) {
for (int j = 0; j <= k; j++) {
dp[i][j][0] = dp[i - 1][j][0] + dp[i - 1][j][1];
if (j > 0) {
dp[i][j][1] = dp[i - 1][j - 1][0];
}
dp[i][j][1] += dp[i - 1][j][1];
}
}
// Total number of ways
int totalWays = dp[n][k][0] + dp[n][k][1];
return totalWays;
}
// Driver Code
public static void main(String[] args) {
int n = 5, k = 2;
int totalWays = waysToKAdjacentSetBits(n, k);
System.out.println("Number of ways = " + totalWays);
}
}
Python
# Function to find the number of Bit Strings
# of length N with K adjacent set bits
def waysToKAdjacentSetBits(n, k):
# dp[i][j][k] represents bit strings of length i
# with f(bit string) = j and last bit as k
dp = [[[0 for i in range(2)] for j in range(k + 1)] for l in range(n + 1)]
# Initializing the base case
# when length of bit string is 1
dp[1][0][1] = 1
dp[1][0][0] = 1
# Filling up the DP Table
for i in range(2, n + 1):
for j in range(k + 1):
dp[i][j][0] = dp[i - 1][j][0] + dp[i - 1][j][1]
if j > 0:
dp[i][j][1] = dp[i - 1][j - 1][0]
dp[i][j][1] += dp[i - 1][j][1]
# Total number of ways
totalWays = dp[n][k][0] + dp[n][k][1]
return totalWays
# Driver Code
if __name__ == '__main__':
n = 5
k = 2
totalWays = waysToKAdjacentSetBits(n, k)
print(f"Number of ways = {totalWays}")
C#
using System;
class MainClass {
static int WaysToKAdjacentSetBits(int n, int k) {
// dp[i][j][k] represents bit strings of length i
// with f(bit string) = j and last bit as k
int[,,] dp = new int[1000, 1000, 2];
// Initializing the base case
// when length of bit string is 1
dp[1, 0, 1] = 1;
dp[1, 0, 0] = 1;
// Filling up the DP Table
for(int i = 2; i <= n; i++) {
for(int j = 0; j <= k; j++) {
dp[i, j, 0] = dp[i-1, j, 0] + dp[i-1, j, 1];
if(j > 0) {
dp[i, j, 1] = dp[i-1, j-1, 0];
}
dp[i, j, 1] += dp[i-1, j, 1];
}
}
// Total number of ways
int totalWays = dp[n, k, 0] + dp[n, k, 1];
return totalWays;
}
public static void Main() {
int n = 5, k = 2;
int totalWays = WaysToKAdjacentSetBits(n, k);
Console.WriteLine("Number of ways = " + totalWays);
}
}
JavaScript
function waysToKAdjacentSetBits(n, k) {
// dp[i][j][k] represents bit strings of length i
// with f(bit string) = j and last bit as k
const dp = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0).map(() => new Array(2).fill(0)));
// Initializing the base case
// when length of bit string is 1
dp[1][0][1] = 1;
dp[1][0][0] = 1;
// Filling up the DP Table
for (let i = 2; i <= n; i++) {
for (let j = 0; j <= k; j++) {
dp[i][j][0] = dp[i - 1][j][0] + dp[i - 1][j][1];
if (j > 0) {
dp[i][j][1] = dp[i - 1][j - 1][0];
}
dp[i][j][1] += dp[i - 1][j][1];
}
}
// Total number of ways
const totalWays = dp[n][k][0] + dp[n][k][1];
return totalWays;
}
// Driver Code
const n = 5, k = 2;
const totalWays = waysToKAdjacentSetBits(n, k);
console.log("Number of ways =", totalWays);
Time Complexity: O(n*k)
Auxiliary Space: O(n*k)
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