Number of Binary Strings of length N with K adjacent Set Bits

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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
?>

chevron_right


Output:

Number of ways = 6

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 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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];
      
    //initilize 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");
}
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

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];
      
    // initilize 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

chevron_right


Output:

Number of ways = 6


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.