Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Count of binary string of length N with X 0s and Y 1s
Next article icon

Count of all possible N length balanced Binary Strings

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number N, the task is to find the total number of balanced binary strings possible of length N. A binary string is said to be balanced if:

  • The number of 0s and 1s are equal in each binary string
  • The count of 0s in any prefix of binary strings is always greater than or equal to the count of 1s
  • For Example: 01 is a balanced binary string of length 2, but 10 is not.

Example:

Input: N = 4
Output: 2
Explanation: Possible balanced binary strings are: 0101, 0011

Input: N = 5
Output: 0

Approach: The given problem can be solved as below:

  1. If N is odd, then no balanced binary string is possible as the condition of an equal count of 0s and 1s will fail.
  2. If N is even, then the N length binary string will have N/2 balanced pair of 0s and 1s.
  3. So, now try to create a formula to get the number of balanced strings when N is even.

So if N = 2, then possible balanced binary string will be "01" only, as "00" and "11" do not have same count of 0s and 1s and "10" does not have count of 0s >= count of 1s in prefix [0, 1).
Similarly, if N=4, then possible balanced binary string will be "0101" and "0011"
For N = 6, then possible balanced binary string will be "010101", "010011", "001101", "000111", and "001011"
Now, If we consider this series:
For N=0, count(0) = 1
For N=2, count(2) = count(0)*count(0) = 1
For N=4, count(4) = count(0)*count(2) + count(2)*count(0) = 1*1 + 1*1 = 2
For N=6, count(6) = count(0)*count(4) + count(2)*count(2) + count(4)*count(0) = 1*2 + 1*1 + 2*1 = 5
For N=8, count(8) = count(0)*count(6) + count(2)*count(4) + count(4)*count(2) + count(6)*count(0) = 1*5 + 1*2 + 2*1 + 5*1 = 14
.
.
.
For N=N, count(N) = count(0)*count(N-2) + count(2)*count(N-4) + count(4)*count(N-6) + .... + count(N-6)*count(4) + count(N-4)*count(2) + count(N-2)*count(0)
which is nothing but Catalan numbers.

  1. Hence for any even N return Catalan number for (N/2) as the answer.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  #define MAXN 500 #define mod 1000000007  // Vector to store catalan number vector<long long int> cat(MAXN + 1, 0);  // Function to get the Catalan Number void catalan() {     cat[0] = 1;     cat[1] = 1;      for (int i = 2; i < MAXN + 1; i++) {         long long int t = 0;         for (int j = 0; j < i; j++) {             t += ((cat[j] % mod)                   * (cat[i - 1 - j] % mod)                   % mod);         }         cat[i] = (t % mod);     } }  int countBalancedStrings(int N) {     // If N is odd     if (N & 1) {         return 0;     }      // Returning Catalan number     // of N/2 as the answer     return cat[N / 2]; }  // Driver Code int main() {     // Precomputing     catalan();      int N = 4;     cout << countBalancedStrings(N); } 
Java
// Java program for the above approach import java.io.*; class GFG {      public static int MAXN = 500;     public static int mod = 1000000007;      // Vector to store catalan number     public static int[] cat = new int[MAXN + 1];      // Function to get the Catalan Number     public static void catalan() {         cat[0] = 1;         cat[1] = 1;          for (int i = 2; i < MAXN + 1; i++) {             int t = 0;             for (int j = 0; j < i; j++) {                 t += ((cat[j] % mod)                         * (cat[i - 1 - j] % mod)                         % mod);             }             cat[i] = (t % mod);         }     }      public static int countBalancedStrings(int N)      {                // If N is odd         if ((N & 1) > 0) {             return 0;         }          // Returning Catalan number         // of N/2 as the answer         return cat[N / 2];     }      // Driver Code     public static void main(String args[])     {                // Precomputing         catalan();          int N = 4;         System.out.println(countBalancedStrings(N));     } }  // This code is contributed by saurabh_jaiswal. 
Python3
# Python3 program for the above approach MAXN = 500 mod = 1000000007  # Vector to store catalan number cat = [0 for _ in range(MAXN + 1)]  # Function to get the Catalan Number def catalan():          global cat      cat[0] = 1     cat[1] = 1      for i in range(2, MAXN + 1):         t = 0         for j in range(0, i):             t += ((cat[j] % mod) *                    (cat[i - 1 - j] % mod) % mod)          cat[i] = (t % mod)  def countBalancedStrings(N):      # If N is odd     if (N & 1):         return 0      # Returning Catalan number     # of N/2 as the answer     return cat[N // 2]  # Driver Code if __name__ == "__main__":      # Precomputing     catalan()      N = 4     print(countBalancedStrings(N))  # This code is contributed by rakeshsahni 
C#
// C# program for the above approach using System; class GFG {     public static int MAXN = 500;     public static int mod = 1000000007;      // Vector to store catalan number     public static int[] cat = new int[MAXN + 1];      // Function to get the Catalan Number     public static void catalan()     {         cat[0] = 1;         cat[1] = 1;          for (int i = 2; i < MAXN + 1; i++)         {             int t = 0;             for (int j = 0; j < i; j++)             {                 t += ((cat[j] % mod)                         * (cat[i - 1 - j] % mod)                         % mod);             }             cat[i] = (t % mod);         }     }      public static int countBalancedStrings(int N)     {          // If N is odd         if ((N & 1) > 0)         {             return 0;         }          // Returning Catalan number         // of N/2 as the answer         return cat[N / 2];     }      // Driver Code     public static void Main()     {          // Precomputing         catalan();          int N = 4;         Console.Write(countBalancedStrings(N));     } }  // This code is contributed by saurabh_jaiswal. 
JavaScript
    <script>          // JavaScript Program to implement         // the above approach          let MAXN = 500         let mod = 1000000007          // Vector to store catalan number         let cat = new Array(MAXN + 1).fill(0);          // Function to get the Catalan Number         function catalan() {             cat[0] = 1;             cat[1] = 1;              for (let i = 2; i < MAXN + 1; i++) {                 let t = 0;                 for (let j = 0; j < i; j++) {                     t += ((cat[j] % mod)                         * (cat[i - 1 - j] % mod)                         % mod);                 }                 cat[i] = (t % mod);             }         }          function countBalancedStrings(N)         {                      // If N is odd             if (N & 1) {                 return 0;             }              // Returning Catalan number             // of N/2 as the answer             return cat[(Math.floor(N / 2))];         }          // Driver Code          // Precomputing         catalan();         let N = 4;         document.write(countBalancedStrings(N));      // This code is contributed by Potta Lokesh     </script> 

Output
2

Time Complexity: O(N2)
Auxiliary Space: O(N)


 


Next Article
Count of binary string of length N with X 0s and Y 1s

C

code_r
Improve
Article Tags :
  • Strings
  • Bit Magic
  • Mathematical
  • Combinatorial
  • DSA
  • binary-string
Practice Tags :
  • Bit Magic
  • Combinatorial
  • Mathematical
  • Strings

Similar Reads

  • Count of binary string of length N with X 0s and Y 1s
    Given positive integers N, X and Y. The task is to find the count of unique binary strings of length N having X 0s and Y 1s. Examples: Input: N=5, X=3, Y=2Output: 10Explanation: There are 10 binary strings of length 5 with 3 0s and 2 1s, such as: 00011, 00101, 01001, 10001, 00110, 01010, 10010, 0110
    4 min read
  • Count of Binary Strings possible as per given conditions
    Given two integers N and M, where N denotes the count of '0' and M denotes the count of '1', and an integer K, the task is to find the maximum number of binary strings that can be generated of the following two types: A string can consist of K '0's and a single '1'.A string can consist of K '1's and
    4 min read
  • Generate all Binary Strings of length N with equal count of 0s and 1s
    Given an integer N, the task is to generate all the binary strings with equal 0s and 1s. If no strings are possible, print -1 Examples: Input: N = 2 Output: “01”, “10”Explanation: All possible binary strings of length 2 are: 01, 10, 11, 00. Out of these, only 2 have equal number of 0s and 1s Input:
    6 min read
  • Count number of binary strings of length N having only 0's and 1's
    Given an integer N, the task is to count the number of binary strings of length N having only 0's and 1's. Note: Since the count can be very large, return the answer modulo 10^9+7. Examples: Input: 2 Output: 4 Explanation: The numbers are 00, 01, 11, 10. Hence the count is 4. Input: 3 Output: 8 Expl
    6 min read
  • Longest balanced binary substring with equal count of 1s and 0s
    Given a binary string str[] of size N. The task is to find the longest balanced substring. A substring is balanced if it contains an equal number of 0 and 1. Examples: Input: str = "110101010"Output: 10101010Explanation: The formed substring contain equal count of 1 and 0 i.e, count of 1 and 0 is sa
    8 min read
  • Count of binary strings of length N having equal count of 0's and 1's
    Given an integer N, the task is to find the number of binary strings possible of length N having same frequency of 0s and 1s. If such string is possible of length N, print -1. Note: Since the count can be very large, return the answer modulo 109+7.Examples: Input: N = 2 Output: 2 Explanation: All po
    6 min read
  • Minimize cost of flipping or swaps to make a Binary String balanced
    Given a binary string S of size N(where N is even), the task is to find the minimum cost of making the given binary string balanced by flipping one of the adjacent different characters at the cost of 1 unit or swap the characters at indices i and j such that (i < j) at the cost of (j - i) unit. I
    6 min read
  • Count N-length Binary Strings consisting of "11" as substring
    Given a positive integer N, the task is to find the number of binary strings of length N which contains "11" as a substring. Examples: Input: N = 2Output: 1Explanation: The only string of length 2 that has "11" as a substring is "11". Input: N = 12Output: 3719 Approach: The idea is to derive the num
    8 min read
  • Count possible binary strings of length N without P consecutive 0s and Q consecutive 1s
    Given three integers N, P, and Q, the task is to count all possible distinct binary strings of length N such that each binary string does not contain P times consecutive 0’s and Q times consecutive 1's. Examples: Input: N = 5, P = 2, Q = 3Output: 7Explanation: Binary strings that satisfy the given c
    15+ min read
  • Count of possible distinct Binary strings after replacing "11" with "0"
    Given a binary string str of size N containing 0 and 1 only, the task is to count all possible distinct binary strings when a substring "11" can be replaced by "0". Examples: Input: str = "11011"Output: 4Explanation: All possible combinations are "11011", "0011", "1100", "000". Input: str = "1100111
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences