Count of substrings of a given Binary string with all characters same - GeeksforGeeks

27 May, 2021
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 which contains only “0”.
Input: str = “0000”Output: 10Explanation: There are no sub-strings having all ones in it.
Naive Approach: The idea is to generate all possible sub-string of the given string. For each sub-string check if the string contains all 1’s or all 0’s. If yes then count that sub-string. Print the count of sub-string after the above operations.
Time Complexity: O(N3)Auxiliary Space: O(N)
Efficient Approach: The idea is to use the concept of Sliding window and Two pointers Approach. Below are the steps to find the count of the substring that contains only 1s:
Initialize two pointers say L and R and initialize them to 0.Now iterate in the given string and check if the current character is equal to 1 or not. If it is, then extend the window by incrementing the value of R.If the current character is 0, then the window L to R – 1 contains all ones.Add the number of sub-strings of L to R – 1 to the answer that is ((R – L) * (R – L + 1)) / 2 and increment R and reinitialize L as R.Repeat the process until L and R cross each other.Print the count of all the substring in step 4.To count the number of substring with all 0s flip the given string i.e., all 0s will be converted into 1s and vice-versa.Repeat the above steps from step 1 to step 4 for character 1 in the flipped string to get a count of the substring that contains only 0s in it and print the count.
Initialize two pointers say L and R and initialize them to 0.
Now iterate in the given string and check if the current character is equal to 1 or not. If it is, then extend the window by incrementing the value of R.
If the current character is 0, then the window L to R – 1 contains all ones.
Add the number of sub-strings of L to R – 1 to the answer that is ((R – L) * (R – L + 1)) / 2 and increment R and reinitialize L as R.
Repeat the process until L and R cross each other.
Print the count of all the substring in step 4.
To count the number of substring with all 0s flip the given string i.e., all 0s will be converted into 1s and vice-versa.
Repeat the above steps from step 1 to step 4 for character 1 in the flipped string to get a count of the substring that contains only 0s in it and print the count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to count number of// sub-strings of a given binary// string that contains only 1int countSubAllOnes(string s){    int l = 0, r = 0, ans = 0;     // Iterate untill L and R cross    // each other    while (l <= r) {         // Check if reached the end        // of string        if (r == s.length()) {            ans += ((r - l) * (r - l + 1)) / 2;            break;        }         // Check if encountered '1'        // then extend window        if (s[r] == '1')            r++;         // Check if encountered '0' then        // add number of strings of        // current window and change the        // values for both l and r        else {             ans += ((r - l) * (r - l + 1)) / 2;            l = r + 1;            r++;        }    }     // Return the answer    return ans;} // Function to flip the bits of stringvoid flip(string& s){     for (int i = 0; s[i]; i++) {        if (s[i] == '1')            s[i] = '0';        else            s[i] = '1';    }  cout<<s<<endl;} // Function to count number of// sub-strings of a given binary// string that contains only 0s & 1sint countSubAllZerosOnes(string s){     // count of substring    // which contains only 1s    int only_1s = countSubAllOnes(s);     // Flip the character of string s    // 0 to 1 and 1 to 0 to count the    // substring with consecutive 0s    flip(s);  cout<<s<<endl;     // count of substring    // which contains only 0s    int only_0s = countSubAllOnes(s);     return only_0s + only_1s;} // Driver Codeint main(){    // Given string str    string s = "011";     // Function Call    cout << countSubAllZerosOnes(s) << endl;    return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to count number of// sub-Strings of a given binary// String that contains only 1static int countSubAllOnes(String s){    int l = 0, r = 0, ans = 0;     // Iterate untill L and R cross    // each other    while (l <= r)    {                 // Check if reached the end        // of String        if (r == s.length())        {            ans += ((r - l) * (r - l + 1)) / 2;            break;        }         // Check if encountered '1'        // then extend window        if (s.charAt(r) == '1')            r++;         // Check if encountered '0' then        // add number of Strings of        // current window and change the        // values for both l and r        else        {            ans += ((r - l) * (r - l + 1)) / 2;            l = r + 1;            r++;        }    }     // Return the answer    return ans;} // Function to flip the bits of Stringstatic String flip(char []s){    for(int i = 0; i < s.length; i++)    {        if (s[i] == '1')            s[i] = '0';        else            s[i] = '1';    }    return String.valueOf(s);} // Function to count number of// sub-Strings of a given binary// String that contains only 0s & 1sstatic int countSubAllZerosOnes(String s){     // count of subString    // which contains only 1s    int only_1s = countSubAllOnes(s);     // Flip the character of String s    // 0 to 1 and 1 to 0 to count the    // subString with consecutive 0s    s = flip(s.toCharArray());     // count of subString    // which contains only 0s    int only_0s = countSubAllOnes(s);     return only_0s + only_1s;} // Driver Codepublic static void main(String[] args){         // Given String str    String s = "011";     // Function call    System.out.print(countSubAllZerosOnes(s) + "\n");}} // This code is contributed by Rohit_ranjan
# Python3 program for# the above approach # Function to count number of# sub-strings of a given binary# string that contains only 1def countSubAllOnes(s):       l, r, ans = 0, 0, 0     # Iterate untill L and R cross    # each other    while (l <= r):         # Check if reached the end        # of string        if (r == len(s)):            ans += ((r - l) *                    (r - l + 1)) // 2            break                # Check if encountered '1'        # then extend window        if (s[r] == '1'):            r += 1         # Check if encountered '0' then        # add number of strings of        # current window and change the        # values for both l and r        else :            ans += ((r - l) *                    (r - l + 1)) // 2            l = r + 1            r += 1     # Return the answer    return ans # Function to flip the bits of stringdef flip(s):          arr = list(s)    for i in range (len(s)):        if (arr[i] == '1'):            arr[i] = '0'        else:            arr[i] = '1'    s = ''.join(arr)    return s # Function to count number of# sub-strings of a given binary# string that contains only 0s & 1sdef countSubAllZerosOnes(s):     # count of substring    # which contains only 1s    only_1s = countSubAllOnes(s)     # Flip the character of string s    # 0 to 1 and 1 to 0 to count the    # substring with consecutive 0s    s = flip(s)     # count of substring    # which contains only 0s    only_0s = countSubAllOnes(s)     return only_0s + only_1s # Driver Codeif __name__ == "__main__":       # Given string str    s  = "011"     # Function Call    print (countSubAllZerosOnes(s))    # This code is contributed by Chitranayal
// C# program for the above approachusing System;class GFG{ // Function to count number of// sub-Strings of a given binary// String that contains only 1static int countSubAllOnes(String s){    int l = 0, r = 0, ans = 0;     // Iterate untill L and R cross    // each other    while (l <= r)    {                 // Check if reached the end        // of String        if (r == s.Length)        {            ans += ((r - l) * (r - l + 1)) / 2;            break;        }         // Check if encountered '1'        // then extend window        if (s[r] == '1')            r++;         // Check if encountered '0' then        // add number of Strings of        // current window and change the        // values for both l and r        else        {            ans += ((r - l) * (r - l + 1)) / 2;            l = r + 1;            r++;        }    }     // Return the answer    return ans;} // Function to flip the bits of Stringstatic String flip(char []s){    for(int i = 0; i < s.Length; i++)    {        if (s[i] == '1')            s[i] = '0';        else            s[i] = '1';    }    return String.Join("",s);} // Function to count number of// sub-Strings of a given binary// String that contains only 0s & 1sstatic int countSubAllZerosOnes(String s){     // count of subString    // which contains only 1s    int only_1s = countSubAllOnes(s);     // Flip the character of String s    // 0 to 1 and 1 to 0 to count the    // subString with consecutive 0s    s = flip(s.ToCharArray());     // count of subString    // which contains only 0s    int only_0s = countSubAllOnes(s);     return only_0s + only_1s;} // Driver Codepublic static void Main(String[] args){         // Given String str    String s = "011";     // Function call    Console.Write(countSubAllZerosOnes(s) + "\n");}} // This code is contributed by Rohit_ranjan
<script> // Javascript program for the above approach // Function to count number of// sub-strings of a given binary// string that contains only 1function countSubAllOnes(s){    var l = 0, r = 0, ans = 0;     // Iterate untill L and R cross    // each other    while (l <= r) {         // Check if reached the end        // of string        if (r == s.length) {            ans += ((r - l) * (r - l + 1)) / 2;            break;        }         // Check if encountered '1'        // then extend window        if (s[r] == '1')            r++;         // Check if encountered '0' then        // add number of strings of        // current window and change the        // values for both l and r        else {             ans += ((r - l) * (r - l + 1)) / 2;            l = r + 1;            r++;        }    }     // Return the answer    return ans;} // Function to flip the bits of stringfunction flip(s){     for (var i = 0; s[i]; i++) {        if (s[i] == '1')            s[i] = '0';        else            s[i] = '1';    }     return s;} // Function to count number of// sub-strings of a given binary// string that contains only 0s & 1sfunction countSubAllZerosOnes(s){     // count of substring    // which contains only 1s    var only_1s = countSubAllOnes(s);     // Flip the character of string s    // 0 to 1 and 1 to 0 to count the    // substring with consecutive 0s    s = flip(s.split(''));     // count of substring    // which contains only 0s    var only_0s = countSubAllOnes(s);     return only_0s + only_1s;} // Driver Code // Given string strvar s = "011"; // Function Calldocument.write( countSubAllZerosOnes(s)); // This code is contributed by famously.</script>
4
 
Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(1)
Rohit_ranjan
ukasp
famously
binary-string
sliding-window
substring
two-pointer-algorithm
Arrays
Greedy
Mathematical
Searching
Strings
sliding-window
two-pointer-algorithm
Arrays
Searching
Strings
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string