Count of Substrings having Sum equal to their Length
Given a numeric string str, the task is to calculate the number of substrings with the sum of digits equal to their length.
Examples:
Input: str = “112112”
Output: 6
Explanation:
Substrings “1”, “1”, “11”, “1”, “1”, “11” satisfy the given condition.
Input: str = “1101112”
Output: 12
Naive Approach: The simplest solution is to generate all substrings of the given string and for each substring, check if its sum is equal to its length or not. For each substring found to be true, increase count.
C++
#include <bits/stdc++.h>
using namespace std;
int countSubstrings(string s, int n)
{
int count = 0;
for ( int i = 0; i < n; i++) {
int sum = 0;
for ( int j = i; j < n; j++) {
sum += s[j] - '0' ;
if (j - i + 1 == sum) {
count++;
}
}
}
return count;
}
int main()
{
string str = "1101112" ;
int n = str.length();
cout << countSubstrings(str, n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static int countSubStrings(String s, int n)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
int sum = 0 ;
for ( int j = i; j < n; j++) {
sum += s.charAt(j) - '0' ;
if (j - i + 1 == sum) {
count++;
}
}
}
return count;
}
public static void main(String[] args)
{
String str = "1101112" ;
int n = str.length();
System.out.print(countSubStrings(str, n) + "\n" );
}
}
|
Python3
def countSubstrings(s: str , n: int ):
count = 0
for i in range (n):
sum = 0
for j in range (i, n):
sum + = int (s[j])
if (j - i + 1 = = sum ):
count + = 1
return count
str = "1101112"
n = len ( str )
print (countSubstrings( str , n))
|
C#
using System;
public class Program {
static int CountSubStrings( string s, int n)
{
int count = 0;
for ( int i = 0; i < n; i++) {
int sum = 0;
for ( int j = i; j < n; j++) {
sum += s[j] - '0' ;
if (j - i + 1 == sum) {
count++;
}
}
}
return count;
}
static void Main( string [] args)
{
string str = "1101112" ;
int n = str.Length;
Console.WriteLine(CountSubStrings(str, n));
}
}
|
Javascript
function countSubstrings( s, n)
{
let count = 0;
for (let i = 0; i < n; i++) {
let sum = 0;
for (let j = i; j < n; j++) {
sum += s[j] - '0' ;
if (j - i + 1 == sum) {
count++;
}
}
}
return count;
}
let str = "1101112" ;
let n = str.length;
console.log(countSubstrings(str, n));
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: We can see that we want the sum of any substring of the string to be equal to its length. Let’s say we already have a prefix array pref calculated such that pref[i] denotes the sum of all the elements from index 0 to index i. Now, we can visualise the question in terms of below given equations:
pref[r] – pref[l-1] = r – l + 1
// taking similar terms together
pref[r] – r = pref[l-1] – l + 1
pref[r] – r = pref[l-1] – (l – 1)
// say i = l – 1
pref[r] – r = pref[i] – i
Now for each index i we just need to check how many times the value of pref[i] – i occured previously. This can be easily solved using a Hashmap and maintaining a sum variable which gives the sum of all elements till index i.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubstrings(string s, int n)
{
int count = 0, sum = 0;
unordered_map< int , int > mp;
mp[0]++;
for ( int i = 0; i < n; ++i) {
sum += (s[i] - '0' );
count += mp[sum - (i + 1)];
++mp[sum - (i + 1)];
}
return count;
}
int main()
{
string str = "112112" ;
int n = str.length();
cout << countSubstrings(str, n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countSubStrings(String s, int n)
{
int count = 0 , sum = 0 ;
HashMap<Integer,
Integer> mp = new HashMap<Integer,
Integer>();
mp.put( 0 , 1 );
for ( int i = 0 ; i < n; ++i)
{
sum += (s.charAt(i)- '0' );
count += mp.containsKey(sum - (i + 1 )) == true ?
mp.get(sum - (i + 1 )) : 0 ;
if (!mp.containsKey(sum - (i + 1 )))
mp.put(sum - (i + 1 ), 1 );
else
mp.put(sum - (i + 1 ),
mp.get(sum - (i + 1 )) + 1 );
}
return count;
}
public static void main(String[] args)
{
String str = "112112" ;
int n = str.length();
System.out.print(countSubStrings(str, n) + "\n" );
}
}
|
Python3
from collections import defaultdict
def countSubstrings(s, n):
count, sum = 0 , 0
mp = defaultdict( lambda : 0 )
mp[ 0 ] + = 1
for i in range (n):
sum + = ord (s[i]) - ord ( '0' )
count + = mp[ sum - (i + 1 )]
mp[ sum - (i + 1 )] + = 1
return count
str = '112112'
n = len ( str )
print (countSubstrings( str , n))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int countSubStrings(String s, int n)
{
int count = 0, sum = 0;
Dictionary< int ,
int > mp = new Dictionary< int ,
int >();
mp.Add(0, 1);
for ( int i = 0; i < n; ++i)
{
sum += (s[i]- '0' );
count += mp.ContainsKey(sum - (i + 1)) == true ?
mp[sum - (i + 1)] : 0;
if (!mp.ContainsKey(sum - (i + 1)))
mp.Add(sum - (i + 1), 1);
else
mp[sum - (i + 1)] = mp[sum - (i + 1)] + 1;
}
return count;
}
public static void Main(String[] args)
{
String str = "112112" ;
int n = str.Length;
Console.Write(countSubStrings(str, n) + "\n" );
}
}
|
Javascript
<script>
function countSubstrings(s, n)
{
var count = 0, sum = 0;
var mp = new Map();
if (mp.has(0))
mp.set(0, mp.get(0)+1)
else
mp.set(0, 1);
for ( var i = 0; i < n; ++i) {
sum += (s[i].charCodeAt(0) - '0' .charCodeAt(0));
if (mp.has(sum - (i + 1)))
count += mp.get(sum - (i + 1));
if (mp.has(sum - (i + 1)))
mp.set(sum - (i + 1), mp.get(sum - (i + 1))+1)
else
mp.set(sum - (i + 1), 1)
}
return count;
}
var str = "112112" ;
var n = str.length;
document.write( countSubstrings(str, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
04 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...