- Related Questions & Answers
- Maximum count of substrings of length K consisting of same characters in C++
- Find the Minimum Number of Fibonacci Numbers Whose Sum Is K in C++
- Count number of substrings with exactly k distinct characters in C++
- Count pairs in array whose sum is divisible by K in C++
- Maximize the number of sum pairs which are divisible by K in C++
- Find K-Length Substrings With No Repeated Characters in Python
- Check whether sum of digits at odd places of a number is divisible by K in Python
- Count subarrays whose product is divisible by k in C++
- Program to count number of paths whose sum is k in python
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Find set of m-elements with difference of any two elements is divisible by k in C++
- Convert all lowercase characters to uppercase whose ASCII value is co-prime with k in C++
- Program to find k where given matrix has k by k square of same value in C++
- Program to find sum of rectangle whose sum at most k in Python
- Find maximum average subarray of k length in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Here we will see another problem, where one string and another integer value say k is given. We have to find the number of substrings of length k, whose sum of ASCII values of characters is divisible by k.

Suppose a string is “BCGABC”. And the value of k is 3. Here string BCG has ASCII sum 300, ABC has ASCII sum 294, both are divisible by k = 3.

The approach is simple. At first we have to find the ASCII value of characters of first substring, whose length is k. We have to use the sliding window technique and subtract ASCII of the first character of the window, and add the ASCII of next character which is coming after sliding the window, we will increase the count at each step, when the sum is divisible by k.

#include <iostream> using namespace std; int countKLenSubstr(string str, int k) { int len = str.length(); int sum = 0; int count = 0 ; for (int i = 0; i <len; i++) sum += str[i] ; //ASCII sum of first substring if (sum % k == 0) count++; for (int i = k; i < len; i++) { int prev_ascii = str[i-k]; //ASCII of the first character of the window sum -= prev_ascii; sum += str[i]; if (sum % k == 0) count += 1; } return count ; } int main() { string s = "BCGABC" ; int k = 3 ; cout<<"Number of substrings: " << countKLenSubstr(s, k); }

Number of substrings: 2

Advertisements