Count of substrings of a given Binary string with all characters same
Last Updated :
02 Jun, 2022
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: 4
Explanation:
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: 10
Explanation:
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.
Below is the implementation of the above approach:
C++
// 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 1
int countSubAllOnes(string s)
{
int l = 0, r = 0, ans = 0;
// Iterate until 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 string
void 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 & 1s
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
flip(s);
cout<<s<<endl;
// count of substring
// which contains only 0s
int only_0s = countSubAllOnes(s);
return only_0s + only_1s;
}
// Driver Code
int main()
{
// Given string str
string s = "011";
// Function Call
cout << countSubAllZerosOnes(s) << endl;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count number of
// sub-Strings of a given binary
// String that contains only 1
static int countSubAllOnes(String s)
{
int l = 0, r = 0, ans = 0;
// Iterate until 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 String
static 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 & 1s
static 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 Code
public 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
# Python3 program for
# the above approach
# Function to count number of
# sub-strings of a given binary
# string that contains only 1
def countSubAllOnes(s):
l, r, ans = 0, 0, 0
# Iterate until 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 string
def 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 & 1s
def 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 Code
if __name__ == "__main__":
# Given string str
s = "011"
# Function Call
print (countSubAllZerosOnes(s))
# This code is contributed by Chitranayal
C#
// C# program for the above approach
using System;
class GFG{
// Function to count number of
// sub-Strings of a given binary
// String that contains only 1
static int countSubAllOnes(String s)
{
int l = 0, r = 0, ans = 0;
// Iterate until 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 String
static 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 & 1s
static 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 Code
public 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
JavaScript
<script>
// Javascript program for the above approach
// Function to count number of
// sub-strings of a given binary
// string that contains only 1
function countSubAllOnes(s)
{
var l = 0, r = 0, ans = 0;
// Iterate until 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 string
function 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 & 1s
function 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 str
var s = "011";
// Function Call
document.write( countSubAllZerosOnes(s));
// This code is contributed by famously.
</script>
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1)
Similar Reads
Count odd length Substrings with median same as Kth character of String Given a string S of size N, the task is to find the number of substrings of odd lengths that have a median equal to the Kth character of the string. Examples: Input: S = "ecadgg", K = 4Output: 4Explanation: Character at 4th position in string is 'd'. Then there are 4 odd length substrings with 'd' a
11 min read
XOR of all substrings of a given Binary String Given a binary string str of size N, the task is to calculate the bitwise XOR of all substrings of str. Examples: Input: str = "11"Output: 11Explanation: The substrings of "11" are: 1, 1, and 11.Their XOR = 1 â 1 â 11 = 11 Input: str = "110"Output: 111Explanation: The substrings of 110 are: 1, 1, 0,
6 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
Count of all unique substrings with non-repeating characters Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
6 min read
Count substrings of a given string whose anagram is a palindrome Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Sinc
10 min read
Find frequency of all characters across all substrings of given string Given a string S containing all lowercase characters and its length N. Find frequency of all characters across all substrings of the given string. Examples: Input: N = 3, S = "aba"Output: a 6b 4Explanation: The substrings are: a, b, a, ab, ba, aba. The frequency of each character: a = 6, b = 4. Henc
4 min read
Count of strings that does not contain any character of a given string Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str. Examples: Input: arr[] = {"abcd", "hijk", "xyz", "ayt"}, str="apple"Output: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
8 min read
Count number of substrings of a string consisting of same characters Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of su
6 min read
Count of substrings of given string with frequency of each character at most K Given a string str, the task is to calculate the number of substrings of the given string such that the frequency of each element of the string is almost K. Examples: Input: str = "abab", K = 1Output: 7Explanation: The substrings such that the frequency of each character is atmost 1 are "a", "b", "a
6 min read
Count substrings with different first and last characters Given a string S, the task is to print the count of substrings from a given string whose first and last characters are different. Examples: Input: S = "abcab"Output: 8Explanation: There are 8 substrings having first and last characters different {ab, abc, abcab, bc, bca, ca, cab, ab}. Input: S = "ab
10 min read