- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

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

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.

## Example

#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); }

## Output

Number of substrings: 2

- Related Questions & Answers
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Maximum count of substrings of length K consisting of same characters in C++
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- Find the Minimum Number of Fibonacci Numbers Whose Sum Is K in C++
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Count number of substrings with exactly k distinct characters in C++
- Count pairs in array whose sum is 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
- Maximize the number of sum pairs which are divisible by K in C++
- Program to count number of paths whose sum is k in python
- Count subarrays whose product is divisible by k in C++
- C++ program to find largest or equal number of A whose sum of digits is divisible by 4
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Program to find sum of rectangle whose sum at most k in Python

Advertisements