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.
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using a Hashmap and keep updating the count of substrings in the Hashmap and print the required count at the end.
Below is the implementation of the above approach:
C++
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std;// Function to count the number of// substrings with sum equal to lengthint countSubstrings(string s, int n){ int count = 0, sum = 0; // Stores the count of substrings unordered_map<int, int> mp; mp[0]++; for (int i = 0; i < n; ++i) { // Add character to sum sum += (s[i] - '0'); // Add count of substrings to result count += mp[sum - (i + 1)]; // Increase count of subarrays ++mp[sum - (i + 1)]; } // Return count return count;}// Driver Codeint main(){ string str = "112112"; int n = str.length(); cout << countSubstrings(str, n) << endl; return 0;} |
Java
// Java program to implement// the above approachimport java.util.*;class GFG{// Function to count the number of// subStrings with sum equal to lengthstatic int countSubStrings(String s, int n){ int count = 0, sum = 0; // Stores the count of subStrings HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); mp.put(0, 1); for(int i = 0; i < n; ++i) { // Add character to sum sum += (s.charAt(i)- '0'); // Add count of subStrings to result count += mp.containsKey(sum - (i + 1)) == true ? mp.get(sum - (i + 1)) : 0; // Increase count of subarrays 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 return count;}// Driver Codepublic static void main(String[] args){ String str = "112112"; int n = str.length(); System.out.print(countSubStrings(str, n) + "\n");}}// This code is contributed by Amit Katiyar |
Python3
# Python3 program to implement # the above approachfrom collections import defaultdict# Function to count the number of # substrings with sum equal to lengthdef countSubstrings(s, n): count, sum = 0, 0 # Stores the count of substrings mp = defaultdict(lambda : 0) mp[0] += 1 for i in range(n): # Add character to sum sum += ord(s[i]) - ord('0') # Add count of substrings to result count += mp[sum - (i + 1)] # Increase count of subarrays mp[sum - (i + 1)] += 1 # Return count return count# Driver codestr = '112112'n = len(str)print(countSubstrings(str, n))# This code is contributed by Stuti Pathak |
C#
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{// Function to count the number of// subStrings with sum equal to lengthstatic int countSubStrings(String s, int n){ int count = 0, sum = 0; // Stores the count of subStrings Dictionary<int, int> mp = new Dictionary<int, int>(); mp.Add(0, 1); for(int i = 0; i < n; ++i) { // Add character to sum sum += (s[i]- '0'); // Add count of subStrings to result count += mp.ContainsKey(sum - (i + 1)) == true ? mp[sum - (i + 1)] : 0; // Increase count of subarrays if(!mp.ContainsKey(sum - (i + 1))) mp.Add(sum - (i + 1), 1); else mp[sum - (i + 1)] = mp[sum - (i + 1)] + 1; } // Return count return count;}// Driver Codepublic static void Main(String[] args){ String str = "112112"; int n = str.Length; Console.Write(countSubStrings(str, n) + "\n");}}// This code is contributed by Rohit_ranjan |
6
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Count of pairs in a given range with sum of their product and sum equal to their concatenated number
- Count of binary strings of length N having equal count of 0's and 1's and count of 1's ≥ count of 0's in each prefix substring
- Count ways to split a Binary String into three substrings having equal count of zeros
- Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
- Count pairs from an array having product of their sum and difference equal to 0
- Count pairs from an array having product of their sum and difference equal to 1
- Possible values of Q such that, for any value of R, their product is equal to X times their sum
- Count pairs from 1 to N such that their Sum is divisible by their XOR
- Check if all substrings of length K of a Binary String has equal count of 0s and 1s
- Split a given string into substrings of length K with equal sum of ASCII values
- Count of binary strings of length N having equal count of 0's and 1's
- Count of subarrays having sum equal to its length
- Count of subarrays having sum equal to its length | Set 2
- Number of ways of choosing K equal substrings of any length for every query
- Minimum flips required to convert given string into concatenation of equal substrings of length K
- Minimize cost to convert given string into concatenation of equal substrings of length K
- Count the number of subsequences of length k having equal LCM and HCF
- Count even length subarrays having bitwise XOR equal to 0
- Count all substrings having character K
- Count of K-size substrings having palindromic permutations
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

