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

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

**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++
  • Java
  • Python3

// 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 length

**int** 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 Code

**int** main()

{

string str = "112112"``;

**int** n = str.length();

cout << countSubstrings(str, n) << endl;

**return** 0;

}

Output:

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.

#greedy #hash #mathematical #searching #strings #cpp-map #frequency-counting #substring

Count of Substrings having Sum equal to their Length
2.00 GEEK