Count Substrings with equal number of 0s, 1s and 2s
Last Updated :
27 Jan, 2023
Given a string that consists of only 0s, 1s and 2s, count the number of substrings that have an equal number of 0s, 1s, and 2s.
Examples:
Input: str = “0102010”
Output: 2
Explanation: Substring str[2, 4] = “102” and substring str[4, 6] = “201” has equal number of 0, 1 and 2
Input: str = “102100211”
Output: 5
Brute Force: To solve the problem using this approach follow the below idea:
Iterate through all substrings of str using nested loops and check whether they contain equal 0,1 and 2 or not.
C++
#include <bits/stdc++.h>
using namespace std;
long long getSubstringWithEqual012(string s) {
vector<string> arr;
int n = s.size();
for ( int i=0;i<n;i++)
{
for ( int j=i;j<n;j++)
{
string s1 = "" ;
for ( int k=i;k<=j;k++)
{
s1+=s[k];
}
arr.push_back(s1);
}
}
int count = 0;
int countZero,countOnes,countTwo;
for ( int i=0;i<arr.size();i++)
{
countZero=0;
countOnes=0;
countTwo=0;
string curs = arr[i];
for ( int j=0;j<curs.size();j++)
{
if (curs[j] == '0' )
countZero++;
if (curs[j] == '1' )
countOnes++;
if (curs[j] == '2' )
countTwo++;
}
if (countZero == countOnes and countOnes == countTwo)
{
count++;
}
}
return count;
}
int main()
{
string str = "0102010" ;
cout << getSubstringWithEqual012(str) << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
static long getSubstringWithEqual012(String s)
{
ArrayList<String> arr = new ArrayList<>();
int n = s.length();
for ( int i = 0 ; i < n; i++) {
for ( int j = i; j < n; j++) {
String s1 = "" ;
for ( int k = i; k <= j; k++) {
s1 += s.charAt(k);
}
arr.add(s1);
}
}
int count = 0 ;
int countZero, countOnes, countTwo;
for ( int i = 0 ; i < arr.size(); i++) {
countZero = 0 ;
countOnes = 0 ;
countTwo = 0 ;
String curs = arr.get(i);
for ( int j = 0 ; j < curs.length(); j++) {
if (curs.charAt(j) == '0' )
countZero++;
if (curs.charAt(j) == '1' )
countOnes++;
if (curs.charAt(j) == '2' )
countTwo++;
}
if (countZero == countOnes
&& countOnes == countTwo) {
count++;
}
}
return count;
}
public static void main(String[] args)
{
String str = "0102010" ;
System.out.println(getSubstringWithEqual012(str));
}
}
|
Python3
def getSubStringWithEqual012(s) :
arr = [];
n = len (s);
for i in range (n):
for j in range (i, n):
s1 = ""
for k in range (i, 1 + j):
s1 + = s[k];
arr.append(s1);
count = 0 ;
for i in range ( len (arr)):
countZero = 0 ;
countOnes = 0 ;
countTwo = 0 ;
curs = arr[i];
for j in range ( len (curs)):
if (curs[j] = = '0' ):
countZero + = 1 ;
if (curs[j] = = '1' ):
countOnes + = 1 ;
if (curs[j] = = '2' ):
countTwo + = 1 ;
if (countZero = = countOnes and countOnes = = countTwo):
count + = 1 ;
return count;
Str = "0102010" ;
print (getSubStringWithEqual012( Str ));
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
static long getSubstringWithEqual012( string s)
{
List< string > arr = new List< string >();
int n = s.Length;
for ( int i = 0; i < n; i++) {
for ( int j = i; j < n; j++) {
String s1 = "" ;
for ( int k = i; k <= j; k++) {
s1 += s[k];
}
arr.Add(s1);
}
}
int count = 0;
int countZero, countOnes, countTwo;
for ( int i = 0; i < arr.Count; i++) {
countZero = 0;
countOnes = 0;
countTwo = 0;
String curs = arr[i];
for ( int j = 0; j < curs.Length; j++) {
if (curs[j] == '0' )
countZero++;
if (curs[j] == '1' )
countOnes++;
if (curs[j] == '2' )
countTwo++;
}
if (countZero == countOnes
&& countOnes == countTwo) {
count++;
}
}
return count;
}
public static void Main( string [] args)
{
string str = "0102010" ;
Console.WriteLine(getSubstringWithEqual012(str));
}
}
|
Javascript
function getSubstringWithEqual012(s) {
let arr = [];
let n = s.length;
for ( var i=0;i<n;i++)
{
for ( var j=i;j<n;j++)
{
var s1 = "" ;
for ( var k=i;k<=j;k++)
{
s1+=s[k];
}
arr.push(s1);
}
}
var count = 0;
var countZero,countOnes,countTwo;
for ( var i=0;i<arr.length;i++)
{
countZero=0;
countOnes=0;
countTwo=0;
var curs = arr[i];
for ( var j=0;j<curs.length;j++)
{
if (curs[j] == '0 ')
countZero++;
if(curs[j] == ' 1 ')
countOnes++;
if(curs[j] == ' 2 ')
countTwo++;
}
// if number of ones,two and zero are equal in a substring
if(countZero == countOnes && countOnes == countTwo)
{
count++;
}
}
return count;
}
// Driver' s code
let str = "0102010" ;
console.log(getSubstringWithEqual012(str));
|
Time Complexity: O(N3)
Auxiliary Space: O(1)
Count Substrings with equal number of 0s, 1s and 2s using Hashing:
Traverse through the string and keep track of counts of 0, 1, and 2 and make a difference pair of (zeroes – ones, zeroes – twos) and increase the answer count if this difference pair is seen before and at every index increase the count of this difference pair in the map
Follow the given steps to solve the problem:
- Declare a map to store the difference pair and three variables to store the count of 0’s, 1’s and 2’s
- Traverse the string and keep track of the count of 0’s, 1’s, and 2’s
- At each index make a difference pair of (zeroes – ones, zeroes – twos)
- Using the map check if this pair is seen before, if it is so then increase the result count
- Then, increase the count of this pair in the map
- Return the result
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getSubstringWithEqual012(string str)
{
int N = str.length();
map<pair< int , int >, int > mp;
mp[make_pair(0, 0)] = 1;
int zc = 0, oc = 0, tc = 0;
int res = 0;
for ( int i = 0; i < N; ++i) {
if (str[i] == '0' )
zc++;
else if (str[i] == '1' )
oc++;
else
tc++;
pair< int , int > tmp = make_pair(zc - oc, zc - tc);
res = res + mp[tmp];
mp[tmp]++;
}
return res;
}
int main()
{
string str = "0102010" ;
cout << getSubstringWithEqual012(str) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
private static int getSubstringWithEqual012(String str)
{
HashMap<String, Integer> map = new HashMap<>();
map.put( "0*0" , 1 );
int zc = 0 , oc = 0 , tc = 0 ;
int ans = 0 ;
for ( int i = 0 ; i < str.length(); i++) {
if (str.charAt(i) == '0' )
zc++;
else if (str.charAt(i) == '1' )
oc++;
else
tc++;
String key = (zc - oc) + "*" + (zc - tc);
ans += map.getOrDefault(key, 0 );
map.put(key, map.getOrDefault(key, 0 ) + 1 );
}
return ans;
}
public static void main(String[] args)
{
String str = "0102010" ;
System.out.println(getSubstringWithEqual012(str));
}
}
|
Python3
def getSubstringWithEqual012(string):
N = len (string)
mp = dict ()
mp[( 0 , 0 )] = 1
zc, oc, tc = 0 , 0 , 0
res = 0
for i in range (N):
if string[i] = = '0' :
zc + = 1
elif string[i] = = '1' :
oc + = 1
else :
tc + = 1
tmp = (zc - oc, zc - tc)
if tmp not in mp:
res + = 0
else :
res + = mp[tmp]
if tmp in mp:
mp[tmp] + = 1
else :
mp[tmp] = 1
return res
if __name__ = = "__main__" :
string = "0102010"
print (getSubstringWithEqual012(string))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
private static int getSubstringWithEqual012( string str)
{
Dictionary< string , int > map = new Dictionary< string , int >();
map.Add( "0*0" , 1);
int zc = 0, oc = 0, tc = 0;
int ans = 0;
for ( int i = 0; i < str.Length; i++)
{
if (str[i] == '0' )
zc++;
else if (str[i] == '1' )
oc++;
else
tc++;
string key = (zc - oc) + "*" + (zc - tc);
if (map.ContainsKey(key))
ans += map[key];
else
map.Add(key, 1);
}
return ans;
}
public static void Main( string [] args)
{
string str = "0102010" ;
Console.WriteLine(getSubstringWithEqual012(str));
}
}
|
Javascript
function getSubstringWithEqual012(string) {
const N = string.length;
const mp = {};
mp[[0, 0]] = 1;
let zc = 0, oc = 0, tc = 0;
let res = 0;
for (let i = 0; i < N; i++) {
if (string[i] === '0' ) {
zc += 1;
} else if (string[i] === '1' ) {
oc += 1;
} else {
tc += 1;
}
const tmp = [zc - oc, zc - tc];
if (!mp.hasOwnProperty(tmp)) {
res += 0;
} else {
res += mp[tmp];
}
if (mp.hasOwnProperty(tmp)) {
mp[tmp] += 1;
} else {
mp[tmp] = 1;
}
}
return res;
}
console.log(getSubstringWithEqual012( "0102010" ));
|
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...