- Related Questions & Answers
- Maximum count of substrings of length K consisting of same 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
- 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++
- Find nth number that contains the digit k or divisible by k in C++
- Count the number of elements in an array which are divisible by k in C++
- Find all possible substrings after deleting k characters in Python
- Product of all the elements in an array divisible by a given number K in C++
- Subarray Sums Divisible by K in C++
- Maximum and Minimum element of a linked list which is divisible by a given number k in C++
- Number of Substrings Containing All Three Characters in C++
- Count all sub-arrays having sum divisible by k
- C++ Program for Largest K digit number divisible by X?

- 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