389. Number of Divisible Substrings

Each character of the English alphabet has been mapped to a digit as shown below.

A string is divisible if the sum of the mapped values of its characters is divisible by its length.

Given a string s, return the number of divisible substrings of s.

A substring is a contiguous non-empty sequence of characters within a string.

Example 1:

Input : s = "abcd"

Output : 6

Explanation :

The possible substrings of given strings are as below :

All substrings of length 1 are divisible substrings i.e. (a, b, c, d).

ab -> 1 + 1 -> 2. Here 2 is divisible by the substring length i.e. 2.

bc -> 1 + 2 -> 3. Here 3 is not divisible by the substring length i.e. 2.

cd -> 2 + 2 -> 4. Here 2 is divisible by the substring length i.e. 2.

abc -> 1 + 1 + 2 -> 4. Here 4 is not divisible by the substring length i.e. 3.

bcd -> 1 + 2 + 2 -> 5. Here 5 is not divisible by the substring length i.e. 3.

abcd -> 1 + 1 + 2 + 2 -> 6. Here 6 is not divisible by the substring length i.e. 4.

So total number of divisible substrings are -> 4 + 2 + 0 -> 6.

Example 2:

Input : s = "xgs"

Output : 5

Explanation :

The possible substrings of given strings are as below :

All substrings of length 1 are divisible substrings i.e. (x, g, x).

xg -> 9 + 3 -> 12. Here 12 is divisible by the substring length i.e. 2.

gs -> 3 + 7 -> 10. Here 10 is divisible by the substring length i.e. 2.

xgs-> 9 + 7 + 3 -> 19. Here 19 is divisible by the substring length i.e. 3.

So total number of divisible substrings are -> 3 + 2 + 0 -> 5.

Now Your Turn!

Pick the correct output for the given input

Input : s = "xmze"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= word.length <= 2000
  • word consists only of lowercase English letters.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int countDivisibleSubstrings(string word) {
//your code goes here
}
};
Test Case

Input:

S