Find number of substrings of length k whose sum of ASCII value of characters is divisible by k in C++

C++Server Side ProgrammingProgramming

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.


 Live Demo

#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)
   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
Updated on 25-Sep-2019 13:14:18