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 Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Count of binary strings of given length consisting of at least one 1
Next article icon

Count binary strings of length same as given string after removal of substrings “01” and “00” that consists of at least one ‘1’

Last Updated : 05 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary string S, the task is to count total binary strings consisting of at least one ‘1’ of length equal to the length of the given string after repeatedly removing all occurrences of substrings “10” and “00” from the given string.

Examples:

Input: S = “111”
Output: 7
Explanation: Since there are no occurrences of “10” or “01” in the given string, length of the remaining string is 3. All possible binary strings of length 3 consisting of at least one set bit are {“001”, “010”, “011”, “100”, “101”, “110”, “111”}

Input: S = “0101”
Output: 3
Explanation: After deleting “10”, S = “01”. Therefore, length of remaining string is 2. Strings of length 2 consisting of at least one set bit are {“01”, “10”, “11”}

Approach: The idea is to calculate the length of the given string after removing all substrings of the form “10” and “00” from it. Considering the remaining; length of the string to be N, the total number of strings consisting of at least one set bit will be equal to 2N-1.

Follow the below steps to solve the problem:

  1. Initialize a variable, say count.
  2. Iterate over the characters of the string S. For each character, check if it is ‘0’ and the count is greater than 0 or not. If found to be true, decrement the count by 1.
  3. Otherwise, if the current character is ‘1’, increment count by 1.
  4. After complete traversal of the string, print 2count – 1 as the required answer.

 Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the strings
// consisting of at least 1 set bit
void countString(string S)
{
    // Initialize count
    long long count = 0;
 
    // Iterate through string
    for (auto it : S) {
 
        if (it == '0' and count > 0) {
            count--;
        }
        else {
            count++;
        }
    }
 
    // The answer is 2^N-1
    cout << ((1 << count) - 1) << "\n";
}
 
// Driver Code
int main()
{
 
    // Given string
    string S = "1001";
 
    // Function call
    countString(S);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
   
class GFG{
   
// Function to count the strings
// consisting of at least 1 set bit
static void countString(String S)
{
     
    // Initialize count
    int count = 0;
     
    // Iterate through string
    for(char it : S.toCharArray())
    {
        if (it == '0' && count > 0)
        {
            count--;
        }
        else
        {
            count++;
        }
    }
  
    // The answer is 2^N-1
    System.out.print((1 << count) - 1);
}
   
// Driver Code
public static void main(String[] args)
{
     
    // Given string
    String S = "1001";
  
    // Function call
    countString(S);
}
}
 
// This code is contributed by susmitakundugoaldanga
 
 

Python3




# Python3 program for the
# above approach 
 
# Function to count the
# strings consisting of
# at least 1 set bit
def countString(S):
   
    # Initialize count
    count = 0
     
    # Iterate through
    # string
    for i in S:
        if (i == '0' and
            count > 0):           
            count -= 1
         
        else:           
            count += 1
 
    # The answer is 2^N-1    
    print((1 << count) - 1) 
 
# Driver Code
if __name__ == "__main__":
 
    # Given string   
    S = "1001"
     
    # Function call   
    countString(S)
 
# This code is contributed by Virusbuddah_
 
 

C#




// C# program for the above approach
using System;
   
class GFG{
   
// Function to count the strings
// consisting of at least 1 set bit
static void countString(string S)
{
     
    // Initialize count
    int count = 0;
     
    // Iterate through string
    foreach(char it in S)
    {
        if (it == '0' && count > 0)
        {
            count--;
        }
        else
        {
            count++;
        }
    }
  
    // The answer is 2^N-1
    Console.Write((1 << count) - 1);
}
   
// Driver Code
public static void Main(string[] args)
{
     
    // Given string
    string S = "1001";
  
    // Function call
    countString(S);
}
}
 
// This code is contributed by chitranayal
 
 

Javascript




<script>
// javascript program for the above approach
 
    // Function to count the strings
    // consisting of at least 1 set bit
    function countString( S) {
 
        // Initialize count
        var count = 0;
 
        // Iterate through string
        for (var it =0;it< S.length; it++) {
            if (S[it] == '0' && count > 0) {
                count--;
            } else {
                count++;
            }
        }
 
        // The answer is 2^N-1
        document.write((1 << count) - 1);
    }
 
    // Driver Code
     
 
        // Given string
        var S = "1001";
 
        // Function call
        countString(S);
 
// This code contributed by umadevi9616
</script>
 
 
Output: 
3

 

Time Complexity: O(L) where L is the length of the string. 
Auxiliary Space: O(1) 



Next Article
Count of binary strings of given length consisting of at least one 1

K

kothawade29
Improve
Article Tags :
  • DSA
  • Searching
  • Strings
  • binary-string
Practice Tags :
  • Searching
  • Strings

Similar Reads

  • Count of binary strings of given length consisting of at least one 1
    Given an integer N, the task is to print the number of binary strings of length N which at least one '1'. Examples: Input: 2 Output: 3 Explanation: "01", "10" and "11" are the possible strings Input: 3 Output: 7 Explanation: "001", "011", "010", "100", "101", "110" and "111" are the possible strings
    3 min read
  • Count of setbits in bitwise OR of all K length substrings of given Binary String
    Given a binary string str of length N, the task is to find the number of setbits in the bitwise OR of all the K length substrings of string str. Examples: Input: N = 4, K = 3, str = "1111"Output: 3Explanation: All 3-sized substrings of S are:"111" and "111". The OR of these strings is "111". Therefo
    8 min read
  • Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
    Given binary string str of length N​​​​, the task is to find the minimum number of characters required to be deleted from the given binary string to make a substring of 0s followed by a substring of 1s. Examples: Input: str = "00101101"Output: 2Explanation: Removing str[2] and str[6] or removing str
    11 min read
  • Count ways to replace '?' in a Binary String to make the count of 0s and 1s same as that of another string
    Given two binary strings S1 and S2 of size N and M respectively such that the string S2 also contains the character '?', the task is to find the number of ways to replace '?' in the string S2 such that the count of 0s and 1s in the string S2 is the same as in the string S1. Examples: Input: S1 = "10
    11 min read
  • Count of binary strings of length N having equal count of 0's and 1's and count of 1's ≥ count of 0's in each prefix substring
    Given an integer N, the task is to find the number of possible binary strings of length N with an equal frequency of 0's and 1's in which frequency of 1's are greater or equal to the frequency of 0's in every prefix substring. Examples: Input: N = 2Output: 1Explanation:All possible binary strings of
    7 min read
  • Count of non-overlapping sub-strings "101" and "010" in the given binary string
    Given binary string str, the task is to find the count of non-overlapping sub-strings of either the form "010" or "101". Examples: Input: str = "10101010101" Output: 3 str[0..2] = "101" str[3..5] = "010" str[6..8] = "101"Input: str = "111111111111110" Output: 0 Approach: Initialize count = 0 and for
    5 min read
  • Check if all substrings of length K of a Binary String has equal count of 0s and 1s
    Given a binary string S of length N and an even integer K, the task is to check if all substrings of length K contains an equal number of 0s and 1s. If found to be true, print “Yes”. Otherwise, print “No”. Examples: Input: S = "101010", K = 2Output: YesExplanation:Since all the substrings of length
    6 min read
  • Find Binary String of size at most 3N containing at least 2 given strings of size 2N as subsequences
    Given three binary strings a, b, and c each having 2*N characters each, the task is to find a string having almost 3*N characters such that at least two of the given three strings occur as its one of the subsequence. Examples: Input: a = "00", b = "11", c = "01"Output: "010"Explanation: The strings
    11 min read
  • Replace '?' to convert given string to a binary string with maximum count of '0' and "10"
    Given string str, consisting of three different types of characters '0', '1' and '?', the task is to convert the given string to a binary string by replacing the '?' characters with either '0' or '1' such that the count of 0s and 10 in the binary string is maximum. Examples: Input: str = 10?0?11Outp
    4 min read
  • Split a Binary String such that count of 0s and 1s in left and right substrings is maximum
    Given a binary string, str of length N, the task is to find the maximum sum of the count of 0s on the left substring and count of 1s on the right substring possible by splitting the binary string into two non-empty substrings. Examples: Input: str = "000111" Output: 6 Explanation: Splitting the bina
    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