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
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Count number of binary strings of length N having only 0's and 1's
Next article icon

Count the number of Binary Strings which have X 1's and Y 0's

Last Updated : 08 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integers X and Y, the task is to count the number of binary strings which have X 1's and Y 0's and there are no two consecutive 1's in the string.

Examples:

Input: X = 2, Y = 2
Output: 3
Explanation: 1010, 0101, 1001 - these are 3 strings that can be possible such that there are no two consecutive 1's.

Input: X = 5, Y = 3
Output: 0
Explanation: There is no such string that can be possible.

Approach: This can be solved with the following idea:

First calculating factorial of both the given numbers and then calculating power of each one will led us to get the desired answer.

Below are the steps involved:

  • Calculating rem Y - X + 1.
    • if rem < 0, return 0.
  • Calculate the factorial of Y+1 and X by calling ncr function.
  • Also, found out the power of both numbers using the binpow function.
  • For the answer, multiply the factorial of X with the power of y.
  • Then final, multiply answer with power of X.
  • Return answer.

Below is the implementation of the code:

C++
// C++ Implementation #include <bits/stdc++.h> using namespace std;  int mod = 1e9 + 7;  // Function to calculate power a^b long long binpow(long long a, long long b) {     long long ans = 1;     while (b) {         if (b % 2 == 1) {             ans = (ans * a) % mod;         }         a = (a * a) % mod;         b = b / 2;     }     return ans; }  // Function to calculate combinations long long ncr(long long a, long long b) {     // Intialising factorial of a, b, c     long long facta = 1;     long long factb = 1;     long long factab = 1;      // Iterating for a     for (int i = a; i >= 1; i--) {          facta = (facta * i);     }      // Iterating for b     for (int j = b; j >= 1; j--) {          factb = (factb * j);     }      long long x = (a - b);      // Iterating for factorial ab     for (int i = x; i >= 1; i--) {          factab = (factab * i);     }      // calculting power     long long invab = binpow(factab, mod - 2);     long long invb = binpow(factb, mod - 2);      long long answer = (facta * invb) % mod;     answer = (answer * invab) % mod;      // Return ans     return answer; }  // Function to count number of strings // that can be constructed int CountString(int x, int y) {      // Calculate rem     long long rem = y - x + 1;      // If rem is negative means no one is there     if (rem < 0) {         return 0;     }      // Calculate combinations     long long answer = ncr(y + 1, x);      // Return answer     return answer; }  // Driver code int main() {      int x = 2;     int y = 2;      // Function call     cout << CountString(x, y);     return 0; } 
Java
import java.util.*;  public class CountString {      static long mod = 1000000007;      // Function to calculate power a^b     static long binpow(long a, long b) {         long ans = 1;         while (b > 0) {             if (b % 2 == 1) {                 ans = (ans * a) % mod;             }             a = (a * a) % mod;             b /= 2;         }         return ans;     }      // Function to calculate combinations     static long ncr(long a, long b) {         // Initializing factorial of a, b, c         long facta = 1;         long factb = 1;         long factab = 1;          // Iterating for a         for (long i = a; i >= 1; i--) {             facta = (facta * i) % mod;         }          // Iterating for b         for (long j = b; j >= 1; j--) {             factb = (factb * j) % mod;         }          long x = a - b;          // Iterating for factorial ab         for (long i = x; i >= 1; i--) {             factab = (factab * i) % mod;         }          // calculating power         long invab = binpow(factab, mod - 2);         long invb = binpow(factb, mod - 2);          long answer = (facta * invb) % mod;         answer = (answer * invab) % mod;          // Return ans         return answer;     }      // Function to count the number of strings that can be constructed     static int countString(int x, int y) {         // Calculate rem         long rem = y - x + 1;          // If rem is negative means no one is there         if (rem < 0) {             return 0;         }          // Calculate combinations         long answer = ncr(y + 1, x);          // Return answer         return (int) answer;     }      // Driver code     public static void main(String[] args) {         int x = 2;         int y = 2;          // Function call         System.out.println(countString(x, y));     } } 
Python3
# Python Implementation  mod = 10**9 + 7  # Function to calculate power a^b def binpow(a, b):     ans = 1     while b > 0:         if b % 2 == 1:             ans = (ans * a) % mod         a = (a * a) % mod         b = b // 2     return ans  # Function to calculate combinations def ncr(a, b):     # Initialize factorial of a, b, and (a-b)     facta = 1     factb = 1     factab = 1      # Iterating for a     for i in range(a, 0, -1):         facta = (facta * i)      # Iterating for b     for j in range(b, 0, -1):         factb = (factb * j)      x = a - b      # Iterating for factorial (a-b)     for i in range(x, 0, -1):         factab = (factab * i)      # Calculate powers     invab = binpow(factab, mod - 2)     invb = binpow(factb, mod - 2)      answer = (facta * invb) % mod     answer = (answer * invab) % mod      # Return the answer     return answer  # Function to count the number of strings # that can be constructed def CountString(x, y):     # Calculate rem     rem = y - x + 1      # If rem is negative, no valid strings can be formed     if rem < 0:         return 0      # Calculate combinations     answer = ncr(y + 1, x)      # Return the answer     return answer  # Driver code x = 2 y = 2  # Function call print(CountString(x, y)) 
C#
// C# Implementation using System;  public class GFG {     static int mod = 1000000007;      // Function to calculate power a^b     static long binpow(long a, long b)     {         long ans = 1;         while (b > 0) {             if (b % 2 == 1) {                 ans = (ans * a) % mod;             }             a = (a * a) % mod;             b = b / 2;         }         return ans;     }      // Function to calculate combinations     static long ncr(long a, long b)     {         // Initializing factorial of a, b, c         long facta = 1;         long factb = 1;         long factab = 1;          // Iterating for a         for (int i = (int)a; i >= 1; i--) {             facta = (facta * i);         }          // Iterating for b         for (int j = (int)b; j >= 1; j--) {             factb = (factb * j);         }          long x = (a - b);          // Iterating for factorial ab         for (int i = (int)x; i >= 1; i--) {             factab = (factab * i);         }          // calculating power         long invab = binpow(factab, mod - 2);         long invb = binpow(factb, mod - 2);          long answer = (facta * invb) % mod;         answer = (answer * invab) % mod;          // Return answer         return answer;     }      // Function to count the number of strings that can be     // constructed     static int CountString(int x, int y)     {         // Calculate rem         long rem = y - x + 1;          // If rem is negative means no one is there         if (rem < 0) {             return 0;         }          // Calculate combinations         long answer = ncr(y + 1, x);          // Return answer         return (int)answer;     }      // Driver code     static void Main()     {         int x = 2;         int y = 2;          // Function call         Console.WriteLine(CountString(x, y));     } }  // This code is contributed by Susobhan Akhuli 
JavaScript
// Javascript program for the above approach const mod = BigInt(10**9 + 7);  // Function to calculate power a^b function binpow(a, b) {     let ans = BigInt(1);     while (b > 0n) {         if (b % 2n === 1n) {             ans = (ans * BigInt(a)) % mod;         }         a = (BigInt(a) * BigInt(a)) % mod;         b = b / 2n;     }     return ans; }  // Function to calculate combinations function ncr(a, b) {     // Initialize factorial of a, b, and (a-b)     let facta = BigInt(1);     let factb = BigInt(1);     let factab = BigInt(1);      // Iterating for a     for (let i = BigInt(a); i >= 1n; i--) {         facta = (facta * i) % mod;     }      // Iterating for b     for (let j = BigInt(b); j >= 1n; j--) {         factb = (factb * j) % mod;     }      let x = BigInt(a - b);      // Iterating for factorial (a-b)     for (let i = x; i >= 1n; i--) {         factab = (factab * i) % mod;     }      // Calculate powers     let invab = binpow(factab, mod - 2n);     let invb = binpow(factb, mod - 2n);      let answer = (facta * invb) % mod;     answer = (answer * invab) % mod;      // Return the answer     return answer; }  // Function to count the number of strings that can be constructed function countString(x, y) {     // Calculate rem     let rem = BigInt(y - x + 1);      // If rem is negative, no valid strings can be formed     if (rem < 0n) {         return 0;     }      // Calculate combinations     let answer = ncr(BigInt(y + 1), BigInt(x));      // Return the answer     return Number(answer); }  // Driver code const x = 2; const y = 2;  // Function call console.log(countString(x, y));  // This code is contributed by Susobhan Akhuli 

Output
3

Time Complexity: O(n*log n)
Auxiliary Space: O(1)


Next Article
Count number of binary strings of length N having only 0's and 1's
https://media.geeksforgeeks.org/auth/avatar.png
Anonymous
Improve
Article Tags :
  • Strings
  • Geeks Premier League
  • DSA
  • binary-string
  • Geeks Premier League 2023
Practice Tags :
  • 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 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
  • Split the binary string into substrings with equal number of 0s and 1s
    Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example: Input
    8 min read
  • Count Substrings with number of 0s and 1s in ratio of X : Y
    Given a binary string S, the task is to count the substrings having the number of 0s and 1s in the ratio of X : Y Examples: Input: S = "010011010100", X = 3, Y = 2Output: 5Explanation: The index range for the 5 substrings are: (0, 4), (2, 6), (6, 10), (7, 11), (2, 11) Input: S = "10010101", X = 1, Y
    7 min read
  • Count of substrings that start and end with 1 in given Binary String
    Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
    12 min read
  • Count number of binary strings without consecutive 1’s : Set 2
    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 = 5 Output: 5 Explanation: The non-negative integers <= 5 with their corresponding binary representations are: 0 : 0 1 : 1 2 : 10 3 : 11 4 :
    15+ min read
  • Count Substrings with equal number of 0s, 1s and 2s
    Given a string that consists of only 0s, 1s and 2s, count the number of substrings that have an equal number of 0s, 1s, and 2s. Examples: Input: str = “0102010”Output: 2Explanation: Substring str[2, 4] = “102” and substring str[4, 6] = “201” has equal number of 0, 1 and 2 Input: str = "102100211"Out
    9 min read
  • Count number of binary strings without consecutive 1's
    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 = 3Output: 5Explanation: 5 strings are ("000", "001", "010", "100", "101"). Input: n = 2Output: 3Explanation: 3 strings are ("00", "01", "10").
    15+ min read
  • Count subarrays with equal number of 1's and 0's
    Given an array arr[] of size n containing 0 and 1 only. The problem is to count the subarrays having an equal number of 0's and 1's. Examples: Input: arr[] = {1, 0, 0, 1, 0, 1, 1}Output: 8Explanation: The index range for the 8 sub-arrays are: (0, 1), (2, 3), (0, 3), (3, 4), (4, 5)(2, 5), (0, 5), (1,
    14 min read
  • Generate Binary String with equal number of 01 and 10 Subsequence
    Given an integer N (N > 2), the task is to generate a binary string of size N that consists of equal numbers of "10" & "01" subsequences and also the string should contain at least one '0' and one '1' Note: If multiple such strings exist, print any. Examples: Input: 4Output: 0110Explanation :
    7 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