Skip to content
Related Articles

Related Articles

Improve Article

Find all even length binary sequences with same sum of first and second half bits

  • Difficulty Level : Medium
  • Last Updated : 17 Sep, 2021

Given a number n, find all binary sequences of length 2n such that sum of first n bits is same as sum of last n bits.
Examples: 
 

Input:  N = 2
Output: 
0101 1111 1001 0110 0000 1010 

Input:  N = 3
Output:  
011011 001001 011101 010001 101011 111111
110011 101101 100001 110101 001010 011110 
010010 001100 000000 010100 101110 100010 
110110 100100 

 

The idea is to fix first and last bits and then recur for remaining 2*(n-1) bits. There are four possibilities when we fix first and last bits –
 

  1. First and last bits are 1, remaining n – 1 bits on both sides should also have the same sum.
  2. First and last bits are 0, remaining n – 1 bits on both sides should also have the same sum.
  3. First bit is 1 and last bit is 0, sum of remaining n – 1 bits on left side should be 1 less than the sum n-1 bits on right side.
  4. First bit is 0 and last bit is 1, sum of remaining n – 1 bits on left side should be 1 more than the sum n-1 bits on right side.

Below is implementation of above idea –
 

C++




// C++ program to print even length binary sequences
// whose sum of first and second half bits is same
#include <bits/stdc++.h>
using namespace std;
 
// Function to print even length binary sequences
// whose sum of first and second half bits is same
 
// diff --> difference between sums of first n bits
// and last n bits
// out --> output array
// start --> starting index
// end --> ending index
void findAllSequences(int diff, char* out, int start, int end)
{
    // We can't cover difference of more than n with 2n bits
    if (abs(diff) > (end - start + 1) / 2)
        return;
 
    // if all bits are filled
    if (start > end)
    {
        // if sum of first n bits and last n bits are same
        if (diff == 0)
            cout << out << " ";
        return;
    }
 
    // fill first bit as 0 and last bit as 1
    out[start] = '0', out[end] = '1';
    findAllSequences(diff + 1, out, start + 1, end - 1);
 
    // fill first and last bits as 1
    out[start] = out[end] = '1';
    findAllSequences(diff, out, start + 1, end - 1);
 
    // fill first and last bits as 0
    out[start] = out[end] = '0';
    findAllSequences(diff, out, start + 1, end - 1);
 
    // fill first bit as 1 and last bit as 0
    out[start] = '1', out[end] = '0';
    findAllSequences(diff - 1, out, start + 1, end - 1);
}
 
// Driver program
int main()
{
    // input number
    int n = 2;
 
    // allocate string containing 2*n characters
    char out[2 * n + 1];
 
    // null terminate output array
    out[2 * n] = '\0';
 
    findAllSequences(0, out, 0, 2*n - 1);
 
    return 0;
}

Java




// Java program to print even length binary
// sequences whose sum of first and second
// half bits is same
import java.io.*;
import java.util.*;
 
class GFG
{
    // Function to print even length binary sequences
    // whose sum of first and second half bits is same
  
    // diff --> difference between sums of first n bits
    // and last n bits
    // out --> output array
    // start --> starting index
    // end --> ending index
    static void findAllSequences(int diff, char out[],
                                     int start, int end)
    {
        // We can't cover difference of more
        // than n with 2n bits
        if (Math.abs(diff) > (end - start + 1) / 2)
            return;
  
        // if all bits are filled
        if (start > end)
        {
            // if sum of first n bits and
            // last n bits are same
            if (diff == 0)
            {
                System.out.print(out);
                System.out.print(" ");
            }   
            return;
        }
  
        // fill first bit as 0 and last bit as 1
        out[start] = '0';
        out[end] = '1';
        findAllSequences(diff + 1, out, start + 1, end - 1);
  
        // fill first and last bits as 1
        out[start] = out[end] = '1';
        findAllSequences(diff, out, start + 1, end - 1);
  
        // fill first and last bits as 0
        out[start] = out[end] = '0';
        findAllSequences(diff, out, start + 1, end - 1);
  
        // fill first bit as 1 and last bit as 0
        out[start] = '1';
        out[end] = '0';
        findAllSequences(diff - 1, out, start + 1, end - 1);
    }
     
    // Driver program
    public static void main (String[] args)
    {
        // input number
        int n = 2;
  
        // allocate string containing 2*n characters
        char[] out = new char[2 * n + 1];
  
        // null terminate output array
        out[2 * n] = '\0';
  
        findAllSequences(0, out, 0, 2*n - 1);
    }
}
 
// This code is contributed by Pramod Kumar

Python3




# Python3 program to print even length binary sequences
# whose sum of first and second half bits is same
 
# Function to print even length binary sequences
# whose sum of first and second half bits is same
 
# diff --> difference between sums of first n bits
# and last n bits
# out --> output array
# start --> starting index
# end --> ending index
def findAllSequences(diff, out, start, end):
 
    # We can't cover difference of more than n with 2n bits
    if (abs(diff) > (end - start + 1) // 2):
        return;
 
    # if all bits are filled
    if (start > end):
        # if sum of first n bits and last n bits are same
        if (diff == 0):
            print(''.join(list(out)),end=" ");
        return;
 
    # fill first bit as 0 and last bit as 1
    out[start] = '0';
    out[end] = '1';
    findAllSequences(diff + 1, out, start + 1, end - 1);
 
    # fill first and last bits as 1
    out[start] = out[end] = '1';
    findAllSequences(diff, out, start + 1, end - 1);
 
    # fill first and last bits as 0
    out[start] = out[end] = '0';
    findAllSequences(diff, out, start + 1, end - 1);
 
    # fill first bit as 1 and last bit as 0
    out[start] = '1';
    out[end] = '0';
    findAllSequences(diff - 1, out, start + 1, end - 1);
 
# Driver program
 
# input number
n = 2;
 
# allocate string containing 2*n characters
out=[""]*(2*n);
 
findAllSequences(0, out, 0, 2*n - 1);
 
# This code is contributed by mits

C#




// C# program to print even length binary
// sequences whose sum of first and second
// half bits is same
using System;
 
class GFG {
     
    // Function to print even length binary
    // sequences whose sum of first and
    // second half bits is same
 
    // diff --> difference between sums of
    // first n bits
    // and last n bits
    // out --> output array
    // start --> starting index
    // end --> ending index
    static void findAllSequences(int diff,
            char []outt, int start, int end)
    {
         
        // We can't cover difference of
        // more than n with 2n bits
        if (Math.Abs(diff) > (end - start
                                   + 1) / 2)
            return;
 
        // if all bits are filled
        if (start > end)
        {
             
            // if sum of first n bits and
            // last n bits are same
            if (diff == 0)
            {
                Console.Write(outt);
                Console.Write(" ");
            }
            return;
        }
 
        // fill first bit as 0 and last bit
        // as 1
        outt[start] = '0';
        outt[end] = '1';
        findAllSequences(diff + 1, outt,
                        start + 1, end - 1);
 
        // fill first and last bits as 1
        outt[start] = outt[end] = '1';
        findAllSequences(diff, outt,
                        start + 1, end - 1);
 
        // fill first and last bits as 0
        outt[start] = outt[end] = '0';
        findAllSequences(diff, outt,
                         start + 1, end - 1);
 
        // fill first bit as 1 and last
        // bit as 0
        outt[start] = '1';
        outt[end] = '0';
        findAllSequences(diff - 1, outt,
                         start + 1, end - 1);
    }
     
    // Driver program
    public static void Main ()
    {
         
        // input number
        int n = 2;
 
        // allocate string containing 2*n
        // characters
        char []outt = new char[2 * n + 1];
 
        // null terminate output array
        outt[2 * n] = '\0';
 
        findAllSequences(0, outt, 0, 2*n - 1);
    }
}
 
// This code is contributed by nitin mittal.

PHP




<?php
// PHP program to print even length binary sequences
// whose sum of first and second half bits is same
 
// Function to print even length binary sequences
// whose sum of first and second half bits is same
 
// diff --> difference between sums of first n bits
// and last n bits
// out --> output array
// start --> starting index
// end --> ending index
function findAllSequences($diff, $out, $start, $end)
{
    // We can't cover difference of more than n with 2n bits
    if (abs($diff) > (int)(($end - $start + 1) / 2))
        return;
 
    // if all bits are filled
    if ($start > $end)
    {
        // if sum of first n bits and last n bits are same
        if ($diff == 0)
            print(implode("",$out)." ");
        return;
    }
 
    // fill first bit as 0 and last bit as 1
    $out[$start] = '0';
    $out[$end] = '1';
    findAllSequences($diff + 1, $out, $start + 1, $end - 1);
 
    // fill first and last bits as 1
    $out[$start] = $out[$end] = '1';
    findAllSequences($diff, $out, $start + 1, $end - 1);
 
    // fill first and last bits as 0
    $out[$start] = $out[$end] = '0';
    findAllSequences($diff, $out, $start + 1, $end - 1);
 
    // fill first bit as 1 and last bit as 0
    $out[$start] = '1';
    $out[$end] = '0';
    findAllSequences($diff - 1, $out, $start + 1, $end - 1);
}
 
// Driver program
 
    // input number
    $n = 2;
 
    // allocate string containing 2*n characters
    $out=array_fill(0,2*$n,"");
 
    findAllSequences(0, $out, 0, 2*$n - 1);
 
// This code is contributed by chandan_jnu
?>

Javascript




<script>
 
    // JavaScript program to print even length binary
    // sequences whose sum of first and second
    // half bits is same
     
    // Function to print even length binary
    // sequences whose sum of first and
    // second half bits is same
  
    // diff --> difference between sums of
    // first n bits
    // and last n bits
    // out --> output array
    // start --> starting index
    // end --> ending index
    function findAllSequences(diff, outt, start, end)
    {
          
        // We can't cover difference of
        // more than n with 2n bits
        if (Math.abs(diff) > parseInt((end - start + 1) / 2, 10))
            return;
  
        // if all bits are filled
        if (start > end)
        {
              
            // if sum of first n bits and
            // last n bits are same
            if (diff == 0)
            {
                document.write(outt.join(""));
                document.write(" ");
            }
            return;
        }
  
        // fill first bit as 0 and last bit
        // as 1
        outt[start] = '0';
        outt[end] = '1';
        findAllSequences(diff + 1, outt, start + 1, end - 1);
  
        // fill first and last bits as 1
        outt[start] = outt[end] = '1';
        findAllSequences(diff, outt, start + 1, end - 1);
  
        // fill first and last bits as 0
        outt[start] = outt[end] = '0';
        findAllSequences(diff, outt, start + 1, end - 1);
  
        // fill first bit as 1 and last
        // bit as 0
        outt[start] = '1';
        outt[end] = '0';
        findAllSequences(diff - 1, outt, start + 1, end - 1);
    }
     
    // input number
    let n = 2;
 
    // allocate string containing 2*n
    // characters
    let outt = new Array(2 * n + 1);
 
    // null terminate output array
    outt[2 * n] = '\0';
 
    findAllSequences(0, outt, 0, 2*n - 1);
     
</script>

Output:  



0101 1111 1001 0110 0000 1010 

Time Complexity: O((4 ^ N   )* N)

4^N because of 4 recursive calls, and N (simplified from 2N) for time spent printing strings of size 2N

Auxiliary Space: O(N) 

There is another approach by which we generate all possible strings of length n and store them in a list at an index representing their sum. Then, we iterate through each each list and generate the strings of size 2n by printing each string with all other strings in the list adding up to the same value.

Python3




def findAllSequences(n):
    sumToString = [[] for x in range(n+1)] # list of strings where index represents sum
    generateSequencesWithSum(n, sumToString, [], 0)
    permuteSequences(sumToString)
 
 
def generateSequencesWithSum(n, sumToString, sequence, sumSoFar):
    #Base case, if there are no more binary digits to include
    if n == 0:
        sumToString[sumSoFar].append("".join(sequence)) #add permutation to list of sequences with sum corresponding to index
        return
    #Generate sequence +0
    sequence.append("0")
    generateSequencesWithSum(n-1, sumToString, sequence, sumSoFar)
    sequence.pop()
    #Generate sequence +1
    sequence.append("1")
    generateSequencesWithSum(n-1, sumToString, sequence, sumSoFar+1)
    sequence.pop()
 
 
def permuteSequences(sumToString):
    #There are 2^n substring in this list of lists
    for sumIndexArr in sumToString:
        # Append
        for sequence1 in sumIndexArr:
            for sequence2 in sumIndexArr:
                print(sequence1 + sequence2)
 
 
findAllSequences(2)
 
#Contribution by Xavier Jean Baptiste

Output:

0000 0101 0110 1001 1010 1111

Time complexity analysis:

generateSequencesWithSum = O((2N)*N)

  • 2N: we generate all permutation of binary strings of size N
  • N: convert the list of characters to a string and store into array. This is done in the base case.

permuteSequences = O((2N) * N!/(N/2)!2 * N)



  • 2N: we iterate through all the string generated of size n
  • N!/(N/2)!2: This one is a bit challenging to explain

let’s take N = 2 as an example. Our array of possible sequence of size n would be:

array index012
list of strings0001,1011

In the list of strings which the index represents the sum, we get get the count of strings of size 2n by using “n choose k” formula. I our case it would be nCk *nCk where k represents the number of 1s in each half of the string of size 2n:

k = 0, we have (2C0)^2 = 1 string (0000)

k =  1, we have (2C1)^2 string = 4 strings(0101 0110 1001 1010)

k = 2, we have (2c2)^2 = 1 string (1111)

We get our longest list of string when k = N/2, hence NCN/2 = N!/[(N/2)! * (N – N/2)!]  which simplifies to NCN/2 = N!/(N/2)!2

Hence, for each element, we must iterate through, at most, NCN/2 for forming strings of length 2N

Without formal proof, if we graph 2^N and N!/(N/2)!2, we see that 2N has a faster growth rate than the latter. Therefore O(2N* N!/(N/2)2 ) < O(2N*2N) = O(22n) = O(4N)

Graph of 2^x and nC(n/2)

  • N: we must print each string of size 2N

Finally we can ignore the time complexity of generateSequencesWithSum because permuteSequence is the leading term

Time complexity: O(2N * N!/(N/2)!2 * N) (better than the first solution of O((4^N) * N, see explanation above for further details)

Auxiliary space: O(2N) because we store all binary string permutations of size N

This article is contributed by Aditya Goel and improved by Xavier Jean Baptiste. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :