Open In App

Count of sub-strings with equal consecutive 0’s and 1’s

Last Updated : 28 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given binary string str of 0’s and 1’s only. The task is to count the total number of substrings of string str such that each substring has an equal number of consecutive 0’s and 1’s in it.

Examples:

Input: str = “010011” 
Output:
Explanation: 
The substrings with consecutive 0’s and 1’s are “01”, “10”, “0011”, “01”. Hence, the count is 4. 
Note: 
The two “01” are at different positions: [0, 1] and [3, 4]. 
“010011” has the same number of 0’s and 1’s but they are not consecutive.

Input: str = “0001110010” 
Output:
Explanation: 
The substrings with consecutive 0’s and 1’s are “000111”, “0011”, “01”, “1100”, “10”, “01”, “10”.

Approach: 

  • Count the number of consecutive 0’s (or 1’s) from start of the string.
  • Then count the number of consecutive 1’s (or 0’s) from the position in the string str where count of 0’s (or 1’s) ends.
  • The total number of substrings with consecutive 0’s and 1’s is the minimum of the count of consecutive 0’s and 1’s found in above two steps.
  • Repeat the above steps till the end of the string str.

Below is the implementation of the above approach: 

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the count of substrings with equal no.
// of consecutive 0's and 1's
int countSubstring(string& S, int& n)
{
    // To store the total count of substrings
    int ans = 0;
 
    int i = 0;
 
    // Traversing the string
    while (i < n) {
 
        // Count of consecutive 0's & 1's
        int cnt0 = 0, cnt1 = 0;
 
        // Counting subarrays of type "01"
        if (S[i] == '0') {
 
            // Count the consecutive 0's
            while (i < n && S[i] == '0') {
                cnt0++;
                i++;
            }
 
            // If consecutive 0's ends then check for
            // consecutive 1's
            int j = i;
 
            // Counting consecutive 1's
            while (j < n && S[j] == '1') {
                cnt1++;
                j++;
            }
        }
 
        // Counting subarrays of type "10"
        else {
 
            // Count consecutive 1's
            while (i < n && S[i] == '1') {
                cnt1++;
                i++;
            }
 
            // If consecutive 1's ends then check for
            // consecutive 0's
            int j = i;
 
            // Count consecutive 0's
            while (j < n && S[j] == '0') {
                cnt0++;
                j++;
            }
        }
 
        // Update the total count of substrings with minimum
        // of (cnt0, cnt1)
        ans += min(cnt0, cnt1);
    }
 
    // Return answer
    return ans;
}
 
// Driver code
int main()
{
    string S = "0001110010";
    int n = S.length();
 
    // Function to print the count of substrings
    cout << countSubstring(S, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C implementation of the above approach
#include <stdio.h>
#include <string.h>
 
// Find minimum between two numbers.
int min(int num1, int num2)
{
    return (num1 > num2) ? num2 : num1;
}
 
// Function to find the count of substrings with equal no.
// of consecutive 0's and 1's
int countSubstring(char S[], int n)
{
    // To store the total count of substrings
    int ans = 0;
 
    int i = 0;
 
    // Traversing the string
    while (i < n) {
 
        // Count of consecutive 0's & 1's
        int cnt0 = 0, cnt1 = 0;
 
        // Counting subarrays of type "01"
        if (S[i] == '0') {
 
            // Count the consecutive 0's
            while (i < n && S[i] == '0') {
                cnt0++;
                i++;
            }
 
            // If consecutive 0's ends then check for
            // consecutive 1's
            int j = i;
 
            // Counting consecutive 1's
            while (j < n && S[j] == '1') {
                cnt1++;
                j++;
            }
        }
 
        // Counting subarrays of type "10"
        else {
 
            // Count consecutive 1's
            while (i < n && S[i] == '1') {
                cnt1++;
                i++;
            }
 
            // If consecutive 1's ends then check for
            // consecutive 0's
            int j = i;
 
            // Count consecutive 0's
            while (j < n && S[j] == '0') {
                cnt0++;
                j++;
            }
        }
 
        // Update the total count of substrings with minimum
        // of (cnt0, cnt1)
        ans += min(cnt0, cnt1);
    }
 
    // Return answer
    return ans;
}
 
// Driver code
int main()
{
    char S[] = "0001110010";
    int n = strlen(S);
 
    // Function to print the count of substrings
    printf("%d", countSubstring(S, n));
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java implementation of the above approach
class GFG {
 
    // Function to find the count of substrings with equal
    // no. of consecutive 0's and 1's
    static int countSubstring(String S, int n)
    {
        // To store the total count of substrings
        int ans = 0;
 
        int i = 0;
 
        // Traversing the string
        while (i < n) {
 
            // Count of consecutive 0's & 1's
            int cnt0 = 0, cnt1 = 0;
 
            // Counting subarrays of type "01"
            if (S.charAt(i) == '0') {
 
                // Count the consecutive 0's
                while (i < n && S.charAt(i) == '0') {
                    cnt0++;
                    i++;
                }
 
                // If consecutive 0's ends then check for
                // consecutive 1's
                int j = i;
 
                // Counting consecutive 1's
                while (j < n && S.charAt(j) == '1') {
                    cnt1++;
                    j++;
                }
            }
 
            // Counting subarrays of type "10"
            else {
 
                // Count consecutive 1's
                while (i < n && S.charAt(i) == '1') {
                    cnt1++;
                    i++;
                }
 
                // If consecutive 1's ends then check for
                // consecutive 0's
                int j = i;
 
                // Count consecutive 0's
                while (j < n && S.charAt(j) == '0') {
                    cnt0++;
                    j++;
                }
            }
 
            // Update the total count of substrings with
            // minimum of (cnt0, cnt1)
            ans += Math.min(cnt0, cnt1);
        }
 
        // Return answer
        return ans;
    }
 
    // Driver code
    static public void main(String args[])
    {
        String S = "0001110010";
        int n = S.length();
 
        // Function to print the count of substrings
        System.out.println(countSubstring(S, n));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 implementation of the
# above approach
 
# Function to find the count
# of substrings with equal no.
# of consecutive 0's and 1's
def countSubstring(S, n) :
 
    # To store the total count
    # of substrings
    ans = 0;
 
    i = 0;
 
    # Traversing the string
    while (i < n) :
 
        # Count of consecutive
        # 0's & 1's
        cnt0 = 0; cnt1 = 0;
 
        # Counting subarrays of
        # type "01"
        if (S[i] == '0') :
 
            # Count the consecutive
            # 0's
            while (i < n and S[i] == '0') :
                cnt0 += 1;
                i += 1;
 
            # If consecutive 0's
            # ends then check for
            # consecutive 1's
            j = i;
 
            # Counting consecutive 1's
            while (j < n and S[j] == '1') :
                cnt1 += 1;
                j += 1;
 
        # Counting subarrays of
        # type "10"
        else :
 
            # Count consecutive 1's
            while (i < n and S[i] == '1') :
                cnt1 += 1;
                i += 1;
 
            # If consecutive 1's
            # ends then check for
            # consecutive 0's
            j = i;
 
            # Count consecutive 0's
            while (j < n and S[j] == '0') :
                cnt0 += 1;
                j += 1;
 
        # Update the total count
        # of substrings with
        # minimum of (cnt0, cnt1)
        ans += min(cnt0, cnt1);
 
    # Return answer
    return ans;
 
# Driver code
if __name__ == "__main__" :
    S = "0001110010";
    n = len(S);
 
    # Function to print the
    # count of substrings
    print(countSubstring(S, n));
     
# This code is contributed by Yash_R


C#




// C# implementation of the
// above approach
using System;
 
class GFG{
 
    // Function to find the count
    // of substrings with equal no.
    // of consecutive 0's and 1's
    static int countSubstring(string S, int n)
    {
        // To store the total count
        // of substrings
        int ans = 0;
     
        int i = 0;
     
        // Traversing the string
        while (i < n) {
     
            // Count of consecutive
            // 0's & 1's
            int cnt0 = 0, cnt1 = 0;
     
            // Counting subarrays of
            // type "01"
            if (S[i] == '0') {
     
                // Count the consecutive
                // 0's
                while (i < n && S[i] == '0') {
                    cnt0++;
                    i++;
                }
     
                // If consecutive 0's
                // ends then check for
                // consecutive 1's
                int j = i;
     
                // Counting consecutive 1's
                while (j < n && S[j] == '1') {
                    cnt1++;
                    j++;
                }
            }
     
            // Counting subarrays of
            // type "10"
            else {
     
                // Count consecutive 1's
                while (i < n && S[i] == '1') {
                    cnt1++;
                    i++;
                }
     
                // If consecutive 1's
                // ends then check for
                // consecutive 0's
                int j = i;
     
                // Count consecutive 0's
                while (j < n && S[j] == '0') {
                    cnt0++;
                    j++;
                }
            }
     
            // Update the total count
            // of substrings with
            // minimum of (cnt0, cnt1)
            ans += Math.Min(cnt0, cnt1);
        }
     
        // Return answer
        return ans;
    }
     
    // Driver code
    static public void Main ()
    {
        string S = "0001110010";
        int n = S.Length;
     
        // Function to print the
        // count of substrings
        Console.WriteLine(countSubstring(S, n));
    }
}
 
// This code is contributed by Yash_R


Javascript




<script>
 
// Javascript implementation of the
// above approach    
 
    // Function to find the count
    // of substrings with equal no.
    // of consecutive 0's and 1's
    function countSubstring( S , n)
    {
        // To store the total count
        // of substrings
        var ans = 0;
 
        var i = 0;
 
        // Traversing the string
        while (i < n) {
 
            // Count of consecutive
            // 0's & 1's
            var cnt0 = 0, cnt1 = 0;
 
            // Counting subarrays of
            // type "01"
            if (S.charAt(i) == '0') {
 
                // Count the consecutive
                // 0's
                while (i < n && S.charAt(i) == '0')
                {
                    cnt0++;
                    i++;
                }
 
                // If consecutive 0's
                // ends then check for
                // consecutive 1's
                var j = i;
 
                // Counting consecutive 1's
                while (j < n && S.charAt(j) == '1')
                {
                    cnt1++;
                    j++;
                }
            }
 
            // Counting subarrays of
            // type "10"
            else {
 
                // Count consecutive 1's
                while (i < n && S.charAt(i) == '1')
                {
                    cnt1++;
                    i++;
                }
 
                // If consecutive 1's
                // ends then check for
                // consecutive 0's
                var j = i;
 
                // Count consecutive 0's
                while (j < n && S.charAt(j) == '0')
                {
                    cnt0++;
                    j++;
                }
            }
 
            // Update the total count
            // of substrings with
            // minimum of (cnt0, cnt1)
            ans += Math.min(cnt0, cnt1);
        }
 
        // Return answer
        return ans;
    }
 
    // Driver code
        var S = "0001110010";
        var n = S.length;
 
        // Function to print the
        // count of substrings
        document.write(countSubstring(S, n));
 
// This code contributed by umadevi9616
 
</script>


Output: 

7

 

Time Complexity: O(N), where N = length of string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.



Similar Reads

Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
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 conditions are { “01010”, “01011”, “01101”, “10101”
19 min read
Count of Binary strings having at most X consecutive 1s and Y consecutive 0s
Given two integers N and M (1 ≤ N, M ≤ 100) denoting the total number of 1s and 0s respectively. The task is to count the number of possible arrangements of these 0s and 1s such that any arrangement has at most X consecutive 1s and Y consecutive 0s (1 ≤ X, Y ≤ 10). As the number of arrangements can be very large, compute the answer with MODULO 109+
7 min read
Count of binary strings of length N having equal count of 0's and 1's and count of 1's &ge; 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 length 2 are {"00", "01", "10" and "11"}. Out of
7 min read
Given a string and an integer k, find the kth sub-string when all the sub-strings are sorted according to the given condition
Given a string str, its sub-strings are formed in such a way that all the sub-strings starting with the first character of the string will occur first in the sorted order of their lengths followed by all the sub-strings starting with the second character of the string in the sorted order of their lengths and so on. For example for the string abc, i
9 min read
Number of sub-strings which are anagram of any sub-string of another string
Given two strings S1 and S2, the task is to count the number of sub-strings of S1 that are anagrams of any sub-string of S2. Examples: Input: S1 = "ABB", S2 = "BAB" Output: 5 There are 6 sub-strings of S1 : "A", "B", "B", "AB", "BB" and "ABB" Out of which only "BB" is the one which is not an anagram of any sub-string of S2. Input: S1 = "PLEASEHELPI
10 min read
Number of sub-sequence such that it has one consecutive element with difference less than or equal to 1
Given an array arr[] of N elements. The task is to find the number of sub-sequences which have at least two consecutive elements such that absolute difference between them is ? 1. Examples: Input: arr[] = {1, 6, 2, 1} Output: 6 {1, 2}, {1, 2, 1}, {2, 1}, {6, 2, 1}, {1, 1} and {1, 6, 2, 1} are the sub-sequences that have at least one consecutive pai
7 min read
Check whether two strings can be made equal by reversing substring of equal length from both strings
Give two strings S1 and S2, the task is to check whether string S1 can be made equal to string S2 by reversing substring from both strings of equal length. Note: A substring can be reversed any number of times. Example: Input: S1 = "abbca", S2 = "acabb" Output: Yes Explanation: The string S1 and S2 can be made equal by: Reverse S1 in the range [2,
12 min read
Count of binary strings of length N with even set bit count and at most K consecutive 1s
Given two integers N and K, the task is to find the number of binary strings of length N having an even number of 1's out of which less than K are consecutive.Examples: Input: N = 4, K = 2 Output: 4 Explanation: The possible binary strings are 0000, 0101, 1001, 1010. They all have even number of 1's with less than 2 of them occurring consecutively.
12 min read
Distinct strings such that they contains given strings as sub-sequences
Given two strings str1 and str2 of lengths M and N respectively. The task is to find all the distinct strings of length M + N such that the frequency of any character in the resultant string is equal to the sum of frequencies of the same character in the given strings and both the given strings are present as a sub-sequence in all the generated str
6 min read