Count of groups of consecutive 1s in a given Binary String - GeeksforGeeks

06 Jul, 2021
Given a binary string S of size N, the task is to find the number of groups of 1s only in the string S.
Examples:
Input: S = “100110111”, N = 9Output: 3Explanation: The following groups are of 1s only:
Group over the range [0, 0] which is equal to “1”.Group over the range [3, 4] which is equal to “11”.Group over the range [6, 8] which is equal to “111”.
Group over the range [0, 0] which is equal to “1”.
Group over the range [3, 4] which is equal to “11”.
Group over the range [6, 8] which is equal to “111”.
Therefore, there are a total of 3 groups of 1s only.
Input: S = “0101”Output: 2
Approach: The problem can be solved by iterating over the characters of the string. Follow the steps below to solve the problem:
Initialize a variable, say count as 0, which stores the number of substrings of 1s in S.
Initialize a stack say st to store the substring before an index of 1s only.
Iterate over the characters of the string S, using the variable i and do the following:If the current character is 1, push 1 into stack st.Otherwise, If st is not empty, increment count by 1. Else Clear st.
If the current character is 1, push 1 into stack st.
Otherwise, If st is not empty, increment count by 1. Else Clear st.
If st is not empty, increment count by 1, i.e If there is a suffix of 1s.
Finally, print the total count obtained.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the number of the// groups of 1s only in the binary// stringint groupsOfOnes(string S, int N){    // Stores number of groups of 1s    int count = 0;     // Initialization of the stack    stack<int> st;     // Traverse the string S    for (int i = 0; i < N; i++) {         // If S[i] is '1'        if (S[i] == '1')            st.push(1);        // Otherwise        else {            // If st is empty            if (!st.empty()) {                count++;                while (!st.empty()) {                    st.pop();                }            }        }    }    // If st is not empty    if (!st.empty())        count++;     // Return answer    return count;}// Driver codeint main(){    // Input    string S = "100110111";    int N = S.length();     // Function call    cout << groupsOfOnes(S, N) << endl;    return 0;}
// Java program for the above approachimport java.util.Stack; class GFG{ // Function to find the number of the// groups of 1s only in the binary// stringstatic int groupsOfOnes(String S, int N){         // Stores number of groups of 1s    int count = 0;     // Initialization of the stack    Stack<Integer> st = new Stack<>();     // Traverse the string S    for(int i = 0; i < N; i++)    {                 // If S[i] is '1'        if (S.charAt(i) == '1')            st.push(1);                     // Otherwise        else        {                         // If st is empty            if (!st.empty())            {                count++;                while (!st.empty())                {                    st.pop();                }            }        }    }         // If st is not empty    if (!st.empty())        count++;     // Return answer    return count;} // Driver codepublic static void main(String[] args){         // Input    String S = "100110111";    int N = S.length();     // Function call    System.out.println(groupsOfOnes(S, N));}} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to find the number of the# groups of 1s only in the binary# stringdef groupsOfOnes(S, N):         # Stores number of groups of 1s    count = 0     # Initialization of the stack    st = []     # Traverse the string S    for i in range(N):                 # If S[i] is '1'        if (S[i] == '1'):            st.append(1)                     # Otherwise        else:                         # If st is empty            if (len(st) > 0):                count += 1                while (len(st) > 0):                    del st[-1]                         # If st is not empty    if (len(st)):        count += 1     # Return answer    return count     # Driver codeif __name__ == '__main__':         # Input    S = "100110111"    N = len(S)         # Function call    print(groupsOfOnes(S, N))     # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the number of the// groups of 1s only in the binary// stringstatic int groupsOfOnes(string S, int N){       // Stores number of groups of 1s    int count = 0;     // Initialization of the stack    Stack<int> st = new Stack<int>();     // Traverse the string S    for (int i = 0; i < N; i++) {         // If S[i] is '1'        if (S[i] == '1')            st.Push(1);        // Otherwise        else {            // If st is empty            if (st.Count > 0) {                count++;                while (st.Count > 0) {                    st.Pop();                }            }        }    }       // If st is not empty    if (st.Count > 0)        count++;     // Return answer    return count;}   // Driver codepublic static void Main(){    // Input    string S = "100110111";    int N = S.Length;     // Function call    Console.Write(groupsOfOnes(S, N));}} // This code is contributed by SURENDRA_GANGWAR.
<script>         // JavaScript program for the above approach         // Function to find the number of the        // groups of 1s only in the binary        // string        function groupsOfOnes(S, N) {            // Stores number of groups of 1s            let count = 0;             // Initialization of the stack            var st = [];             // Traverse the string S            for (let i = 0; i < N; i++) {                 // If S[i] is '1'                if (S[i] == '1')                    st.push(1);                // Otherwise                else {                    // If st is empty                    if (st.length != 0) {                        count++;                        while (st.length != 0) {                            st.pop();                        }                    }                }            }            // If st is not empty            if (st.length != 0)                count++;             // Return answer            return count;        }        // Driver code         // Input        var S = "100110111";        let N = S.length;         // Function call        document.write(groupsOfOnes(S, N)); // This code is contributed by Potta Lokesh </script>
3
Time Complexity: O(N)Auxiliary Space: O(N)
 
mohit kumar 29
lokeshpotta20
abhinavjain194
SURENDRA_GANGWAR
binary-string
Bit Magic
Stack
Strings
Strings
Stack
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Program to find whether a given number is power of 2
Binary representation of a given number
Add two numbers without using arithmetic operators
Stack Data Structure (Introduction and Program)
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Program for Tower of Hanoi