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:
Split the binary string into substrings with equal number of 0s and 1s
Next article icon

Check if N sized String with given number of 00, 01, 10, 11 Substrings exists

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

Given an integer N and four values a, b, c, d (where a ≥ 0, b ≥ 0, c ≥ 0, d ≥ 0), the task is to check if it is possible to create a binary string of length N such that:

  • There are exactly a substrings of "00" 
  • There are exactly b substrings of "01"
  • There are exactly c substrings of "10"
  • There are exactly d substrings of "11"

Examples:

Input:  N = 11, a = 2, b = 3, c = 3, d = 2
Output : Yes 
Explanation : In this string, exactly 2 numbers of 00, exactly 3 numbers 01, exactly 3 numbers of 10 and exactly 2 numbers of 11.

Input : N = 11, a = 0, b = 3, c = 3, d = 0
Output: No 
Explanation : We can make a string with exactly 3 numbers of 01 and 3 numbers of 10, but string size will be 7, so can't possible to make a perfect binary string with 11 length.

Input: N = 4, a = 1, b = 0, c = 0, d = 1
Output: No
Explanation : We can't make a string because if 00 are there and 11 are there, it is must that 01 or 10 will be there in junction of 00 and 11  

Observation:

We have to check the cases where string can't be formed.

  • Case 1: when number of  01 and 10 pairs are zero, then it can't be possible to create a string if 00 and 11 pairs appears non-zero times. Because, these are required to form  a 01 or 10 in the junction of 00 and 11.
  • Case 2: when b and c are the number of  01 and 10 pairs, then it is not possible to create a string if abs(b-c)>1.
  • Case 3: If case 1 and case 2 are not happening and string is formed with exact pairs of 00, 11, 10, 01 and if the length of the string is not equal to n, then the string is not possible.

Approach: Follow the below approach to solve the problem:

  • Check if 01 and 10 appear zero times and 00 and 11 appear non-zero times then it is not possible to create such binary string.
  • Check if the absolute difference between numbers 01 and 10 is:
    • Greater than 1, abs(b - c) > 1, then it is not possible to create a string.
    • Equal to 1, calculate the length of the string, if it is equal to n, return true, else return false.
    • Equal to 0, calculate the length of the string, if it is equal to n, return true, else return false.

Steps were to follow the above approach:

  • Initialize a variable say, sum = 0 to calculate the length of the string.
  • Check if b == 0 && c == 0 && d != 0 && a != 0, then it is not possible to create a perfect binary string, return false.
  • Check if abs(b - c) > 1, then it is not possible to create a perfect binary string, return false.
  • Check if abs(b - c) == 1, and calculate the length of the string, by updating the sum
    • Add max(b, c) * 2 to sum
    • Add 'a' to sum
    • Add 'd' to the sum
    • Increment sum by 1.
  • Check if sum != n, return false, else return true.
  • Check if b == c, calculate the length of the string, and check if sum != n, return false, else return true.

Below is the implementation for the above approach:

C++
// C++ code for the above approach #include <bits/stdc++.h> using namespace std;  // Function to check if it possible to // create the required binary string bool requiredString(int n, int a, int b, int c, int d) {      // Initialize a integer variable sum     // to calculate the length     // of the string     int sum = 0;      // Check if 01 and 10 are appears zero     // times and 00 and 11 appears non-zero     // times then it is not possible to     // create a perfect binary string     if (b == 0 && c == 0 && d != 0 && a != 0) {         return false;     }      // If absolute difference between 01     // and 10 are greater than 1 then not     // possible to create a string.     else if (abs(b - c) > 1) {         return false;     }      // If absolute difference between 01     // and 10 are equal to 1 then check     // the length of the string, if the     // length is equal to n     else if (abs(b - c) == 1) {         sum += max(b, c) * 2;         sum += a;         sum += d;          if (sum != n) {             return false;         }     }      // If absolute difference between 01     // and 10 are equal to 0 then check     // the length of the string, if the     // length is equal to n     else if (b == c) {         sum += max(b, c) * 2;         sum += a;         sum += d;         sum += 1;         if (sum != n) {             return false;         }     }     return true; }  // Driver Code int main() {      // Given five integers     int n = 11, a = 2, b = 3, c = 3, d = 2;      if (requiredString(n, a, b, c, d)) {         cout << "Yes" << endl;     }     else {         cout << "No" << endl;     }      return 0; } 
Java
// Java code for the above approach import java.util.*;  class GFG {      // Function to check if it possible to     // create the required binary string     static boolean requiredString(int n, int a, int b,                                   int c, int d)     {          // Initialize a integer variable sum         // to calculate the length         // of the string         int sum = 0;          // Check if 01 and 10 are appears zero         // times and 00 and 11 appears non-zero         // times then it is not possible to         // create a perfect binary string         if (b == 0 && c == 0 && d != 0 && a != 0) {             return false;         }          // If absolute difference between 01         // and 10 are greater than 1 then not         // possible to create a string.         else if (Math.abs(b - c) > 1) {             return false;         }          // If absolute difference between 01         // and 10 are equal to 1 then check         // the length of the string, if the         // length is equal to n         else if (Math.abs(b - c) == 1) {             sum += Math.max(b, c) * 2;             sum += a;             sum += d;              if (sum != n) {                 return false;             }         }          // If absolute difference between 01         // and 10 are equal to 0 then check         // the length of the string, if the         // length is equal to n         else if (b == c) {             sum += Math.max(b, c) * 2;             sum += a;             sum += d;             sum += 1;             if (sum != n) {                 return false;             }         }         return true;     }      // Driver Code     public static void main(String[] args)     {          // Given five integers         int n = 11, a = 2, b = 3, c = 3, d = 2;          if (requiredString(n, a, b, c, d)) {             System.out.println("Yes");         }         else {             System.out.println("No");         }     } }  // This code is contributed by prasad264 
Python3
# Python code for the above approach  # Function to check if it possible to create the required binary string def requiredString(n, a, b, c, d):      # Initialize a integer variable sum     # to calculate the length of the string     sum = 0      # Check if 01 and 10 are appears zero times and 00 and 11 appears non-zero times     # then it is not possible to create a perfect binary string     if b == 0 and c == 0 and d != 0 and a != 0:         return False      # If absolute difference between 01 and 10      # are greater than 1 then not possible to create a string.     elif abs(b - c) > 1:         return False      # If absolute difference between 01 and 10 are      # equal to 1 then check the length of the string,     # if the length is equal to n     elif abs(b - c) == 1:         sum += max(b, c) * 2         sum += a         sum += d          if sum != n:             return False     # If absolute difference between 01 and 10     # are equal to 0 then check the length of the string,     # if the length is equal to n     elif b == c:         sum += max(b, c) * 2         sum += a         sum += d         sum += 1         if sum != n:             return False      return True   # Driver code n = 11 a = 2 b = 3 c = 3 d = 2  if requiredString(n, a, b, c, d):     print("Yes") else:     print("No") # This code is contributed by rutikbhosale 
C#
// C# code for the above approach using System;  class Program {     // Function to check if it possible to     // create the required binary string     static bool RequiredString(int n, int a, int b, int c,                                int d)     {          // Initialize a integer variable sum         // to calculate the length         // of the string         int sum = 0;          // Check if 01 and 10 are appears zero         // times and 00 and 11 appears non-zero         // times then it is not possible to         // create a perfect binary string         if (b == 0 && c == 0 && d != 0 && a != 0) {             return false;         }          // If absolute difference between 01         // and 10 are greater than 1 then not         // possible to create a string.         else if (Math.Abs(b - c) > 1) {             return false;         }          // If absolute difference between 01         // and 10 are equal to 1 then check         // the length of the string, if the         // length is equal to n         else if (Math.Abs(b - c) == 1) {             sum += Math.Max(b, c) * 2;             sum += a;             sum += d;              if (sum != n) {                 return false;             }         }          // If absolute difference between 01         // and 10 are equal to 0 then check         // the length of the string, if the         // length is equal to n         else if (b == c) {             sum += Math.Max(b, c) * 2;             sum += a;             sum += d;             sum += 1;             if (sum != n) {                 return false;             }         }         return true;     }      // Driver Code     static void Main(string[] args)     {         // Given five integers         int n = 11, a = 2, b = 3, c = 3, d = 2;          if (RequiredString(n, a, b, c, d)) {             Console.WriteLine("Yes");         }         else {             Console.WriteLine("No");         }     } } 
JavaScript
// Function to check if it is possible to create the required binary string function requiredString(n, a, b, c, d) {   let sum = 0;    // Check if 01 and 10 are not appearing and 00 and 11 are appearing non-zero times, then it is not possible to create a perfect binary string   if (b === 0 && c === 0 && d !== 0 && a !== 0) {     return false;   }    // If absolute difference between 01 and 10 are greater than 1, then it is not possible to create a string   else if (Math.abs(b - c) > 1) {     return false;   }    // If absolute difference between 01 and 10 are equal to 1, then check the length of the string, if the length is equal to n   else if (Math.abs(b - c) === 1) {     sum += Math.max(b, c) * 2;     sum += a;     sum += d;      if (sum !== n) {       return false;     }   }    // If absolute difference between 01 and 10 are equal to 0, then check the length of the string, if the length is equal to n   else if (b === c) {     sum += Math.max(b, c) * 2;     sum += a;     sum += d;     sum += 1;      if (sum !== n) {       return false;     }   }    return true; }  // Driver code const n = 11; const a = 2; const b = 3; const c = 3; const d = 2;  if (requiredString(n, a, b, c, d)) {   console.log("Yes"); } else {   console.log("No"); } 

Output
Yes

Time Complexity: O(1)
Auxiliary Space: O(1)


Next Article
Split the binary string into substrings with equal number of 0s and 1s
author
sowham18
Improve
Article Tags :
  • Strings
  • DSA
  • substring
Practice Tags :
  • Strings

Similar Reads

  • Check if substring "10" occurs in the given binary string in all possible replacements of '?' with 1 or 0
    Given a string S consisting of only '0', '1' and '?', the task is to check if there exists a substring "10" in every possible replacement of the character '?' with either 1 or 0. Examples: Input: S = "1?0"Output: YesExplanation:Following are all the possible replacements of '?': Replacing the '?' wi
    7 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
  • Min Length String with All Substrings of Size N
    Given two integers n and k, your task is to find a string of minimum length to contain all possible strings of size n as a substring. The characters of the string should be integers ranging from 0 to k - 1. Examples: Input: n = 2, k = 2Output: 00110Explanation: Allowed characters are from 0 to k-1 (
    7 min read
  • Count of substrings of a given Binary string with all characters same
    Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = “011”Output: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
    10 min read
  • Check if given number contains only “01” and “10” as substring in its binary representation
    Given a number N, the task is to check if the binary representation of the number N has only "01" and "10" as a substring or not. If found to be true, then print "Yes". Otherwise, print "No".Examples: Input: N = 5 Output: Yes Explanation: (5)10 is (101)2 which contains only "01" and "10" as substrin
    6 min read
  • Maximum count of unique index 10 or 01 substrings in given Binary string
    Given a binary string str of length N, the task is to count the maximum number of adjacent pairs of form "01" or "10" that can be formed from the given binary string when one character can be considered for only one pair. Note: Adjacent pair means pair formed using adjacent characters. Examples: Inp
    5 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
  • Number of sub-strings in a given binary string divisible by 2
    Given binary string str of length N, the task is to find the count of substrings of str which are divisible by 2. Leading zeros in a substring are allowed. Examples: Input: str = "101" Output: 2 "0" and "10" are the only substrings which are divisible by 2. Input: str = "10010" Output: 10 Naive appr
    4 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
  • Check if given string can be split into four distinct strings
    Given a string, the task is to check if we can split it into 4 strings such that each string is non-empty and different from the other. Examples: Input : str[] = "geeksforgeeks"Output : Yes"geeks", "for", "gee", "ks" are four distinct strings that can form from given string.Input : str[] = "aaabb"Ou
    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