Open In App

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

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string and a number k, the task is to find the number of substrings of length k whose sum of the ASCII value of characters is divisible by k.

Examples:

 
Input : str = “bcgabc”, k = 3 
Output :
Substring “bcg” has sum of ASCII values 300 and “abc” has sum of ASCII values 294 which are divisible by 3.

Input : str = “adkf”, k = 3 
Output :

Brute Force Approach:

The brute force approach to solve this problem is to generate all possible substrings of length k from the given string and calculate the sum of ASCII values of characters for each substring. Then check whether the sum is divisible by k or not. If it is divisible by k, then count it as a valid substring. Finally, return the count of valid substrings.

Below is the implementation of the above approach:  

C++




#include<bits/stdc++.h>
using namespace std;
 
int count(string s, int k)
{
    int n = s.length();
    int cnt = 0;
    for (int i = 0; i <= n - k; i++)
    {
        int sum = 0;
        for (int j = i; j < i + k; j++)
            sum += s[j];
        if (sum % k == 0)
            cnt++;
    }
    return cnt;
}
 
int main()
{
    string s = "adkf";
    int k = 3;
    int ans = count(s, k);
    cout << ans;
    return 0;
}


Java




import java.util.*;
 
public class Main {
  public static int count(String s, int k) {
    int n = s.length();
    int cnt = 0;
    for (int i = 0; i <= n - k; i++) {
      int sum = 0;
      for (int j = i; j < i + k; j++)
        sum += s.charAt(j);
      if (sum % k == 0)
        cnt++;
    }
    return cnt;
  }
 
  public static void main(String[] args) {
    String s = "adkf";
    int k = 3;
    int ans = count(s, k);
    System.out.println(ans);
  }
}


Python3




def count(s, k):
    n = len(s)
    cnt = 0
    for i in range(n - k + 1):
        _sum = 0
        for j in range(i, i + k):
            _sum += ord(s[j])
        if _sum % k == 0:
            cnt += 1
    return cnt
 
s = "adkf"
k = 3
ans = count(s, k)
print(ans)


C#




using System;
 
class GFG {
    public static int Count(string s, int k) {
        int n = s.Length;
        int cnt = 0;
        for (int i = 0; i <= n - k; i++) {
            int sum = 0;
            for (int j = i; j < i + k; j++) {
                sum += s[j];
            }
            if (sum % k == 0) {
                cnt++;
            }
        }
        return cnt;
    }
 
    public static void Main(string[] args) {
        string s = "adkf";
        int k = 3;
        int ans = Count(s, k);
        Console.WriteLine(ans);
    }
}


Javascript




// JavaScript code
function count(s, k) {
    let n = s.length;
    let cnt = 0;
    for (let i = 0; i <= n - k; i++) {
        let sum = 0;
        for (let j = i; j < i + k; j++) {
            sum += s.charCodeAt(j);
        }
        if (sum % k === 0) {
            cnt++;
        }
    }
    return cnt;
}
 
let s = "adkf";
let k = 3;
let ans = count(s, k);
console.log(ans);


Output

1


Time Complexity: O(N^2)
Space Complexity: O(1)

Approach: First, we find the sum of ASCII value of characters of first substring of length k, then using sliding window technique subtract ASCII value of first character of the previous substring and add ASCII value of the current character. We will increase the counter at each step if sum is divisible by k.

Below is the implementation of the above approach:  

C++




// C++ program to find number of substrings
// of length k whose sum of ASCII value of
// characters is divisible by k
#include<bits/stdc++.h>
using namespace std;
 
int count(string s, int k)
{
     
    // Finding length of string
    int n = s.length();
    int d = 0 ,i;
    int count = 0 ;
     
    for (i = 0; i <n; i++)
        // finding sum of ASCII value of first
        // substring
        d += s[i] ;
     
    if (d % k == 0)
        count += 1 ;
     
    for (i = k; i < n; i++)
    {
     
        // Using sliding window technique to
        // find sum of ASCII value of rest of
        // the substring
        int prev = s[i-k];
        d -= prev;
        d += s[i];
     
     
     
        // checking if sum is divisible by k
        if (d % k == 0)
        count += 1;
    }
     
    return count ;
    }
     
    // Driver code
    int main()
    {
         
        string s = "bcgabc" ;
        int k = 3 ;
        int ans = count(s, k);
        cout<<(ans);
    }
    // This code is contributed by
    // Sahil_Shelangia


Java




// Java program to find number of substrings
// of length k whose sum of ASCII value of
// characters is divisible by k
 
 
public class GFG{
 
    static int count(String s, int k){
     
    // Finding length of string
    int n = s.length() ;
    int d = 0 ,i;
    int count = 0 ;
     
    for (i = 0; i <n; i++)
        // finding sum of ASCII value of first
        // substring
        d += s.charAt(i) ;
     
    if (d % k == 0)
        count += 1 ;
     
    for (i = k; i < n; i++)
    {
     
        // Using sliding window technique to
        // find sum of ASCII value of rest of
        // the substring
        int prev = s.charAt(i-k) ;
        d -= prev ;
        d += s.charAt(i) ;
     
     
     
        // checking if sum is divisible by k
        if (d % k == 0)
        count += 1 ;
    }
     
    return count ;
    }
     
    // Driver code
    public static void main(String[]args) {
         
        String s = "bcgabc" ;
        int k = 3 ;
        int ans = count(s, k);
        System.out.println(ans);
    }
    // This code is contributed by Ryuga
}


Python3




# Python3 program to find number of substrings
# of length k whose sum of ASCII value of
# characters is divisible by k
 
def count(s, k):
     
    # Finding length of string
    n = len(s)
    d, count = 0, 0
    for i in range(k):
         
        # finding sum of ASCII value of first
        # substring
        d += ord(s[i])
        if (d % k == 0):
            count += 1
            for i in range(k, n):
                 
                # Using sliding window technique to
                # find sum of ASCII value of rest of
                # the substring
                prev = ord(s[i-k])
                d -= prev
                d += ord(s[i])
                 
                # checking if sum is divisible by k
                if (d % k == 0):
                    count += 1
                    return count
# Driver code
s = "bcgabc"
k = 3
ans = count(s, k)
print(ans)


C#




// C# program to find number of substrings
// of length k whose sum of ASCII value of
// characters is divisible by k
  
  
using System;
public class GFG{
  
    static int count(string s, int k){
      
    // Finding length of string
    int n = s.Length ;
    int d = 0 ,i;
    int count = 0 ;
      
    for (i = 0; i <n; i++)
        // finding sum of ASCII value of first
        // substring
        d += s[i] ;
      
    if (d % k == 0)
        count += 1 ;
      
    for (i = k; i < n; i++)
    {
      
        // Using sliding window technique to
        // find sum of ASCII value of rest of
        // the substring
        int prev = s[i-k] ;
        d -= prev ;
        d += s[i] ;
      
      
      
        // checking if sum is divisible by k
        if (d % k == 0)
        count += 1 ;
    }
      
    return count ;
    }
      
    // Driver code
    public static void Main() {
          
        string s = "bcgabc" ;
        int k = 3 ;
        int ans = count(s, k);
        Console.Write(ans);
    }
   
}


Javascript




<script>
 
// JavaScript program to find number of
// substrings of length k whose sum of
// ASCII value of characters is divisible by k
function count(s, k)
{
     
    // Finding length of string
    var n = s.length;
    var d = 0, i;
    var count = 0;
     
    for(i = 0; i < n; i++)
     
        // Finding sum of ASCII value of first
        // substring
        d += s[i].charCodeAt(0);
         
        if (d % k === 0)
        {
            count += 1;
        }
         
        for(i = k; i < n; i++)
        {
             
            // Using sliding window technique to
            // find sum of ASCII value of rest of
            // the substring
            var prev = s[i - k];
            d -= prev.charCodeAt(0);
            d += s[i].charCodeAt(0);
             
            // checking if sum is divisible by k
            if (d % k === 0)
                count += 1;
        }
         
    return count;
}
 
// Driver code
var s = "bcgabc";
var k = 3;
var ans = count(s, k);
 
document.write(ans);
 
// This code is contributed by rdtank
 
</script>


Output

2


Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.



Similar Reads

Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one
Given a string S consisting of lowercase English alphabets, the task is to find the length of the longest subsequence from the given string such that the difference between the largest and smallest ASCII value is exactly 1. Examples: Input: S = "acbbebcg"Output: 5Explanation: The longest subsequence of required type is "cbbbc", whose length is 5.Th
6 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read
Count pairs of characters in a string whose ASCII value difference is K
Given string str of lower case alphabets and a non-negative integer K. The task is to find the number of pairs of characters in the given string whose ASCII value difference is exactly K. Examples: Input: str = "abcdab", K = 0 Output: 2 (a, a) and (b, b) are the only valid pairs.Input: str = "geeksforgeeks", K = 1 Output: 8 (e, f), (e, f), (f, e),
7 min read
Convert all lowercase characters to uppercase whose ASCII value is co-prime with k
Given an integer 'k' and a string 'str' consisting of characters from English alphabets. The task is to convert all lower case character to uppercase whose ASCII value is co-prime with k. Examples: Input: str = "geeksforgeeks", k = 4 Output: GEEKSfOrGEEKS 'f' and 'r' are the only characters whose ASCII values aren't co-prime with 4. Input: str = "A
6 min read
Split a given string into substrings of length K with equal sum of ASCII values
Given a string str of size N and an integer K, the task is to check if the input string can be partitioned into substrings of size K having a constant sum of ASCII values.Examples: Input: str = "abdcbbdba" K = 3 Output: YES Explanation: 3 length substrings {"and", "cbb", "dba"} with sum of their ASCII values equal to 295.Input: str = "ababcdabas" K
6 min read
Check if a string contains a non-ASCII value in Julia - ascii() Method
The ascii() is an inbuilt function in Julia which is used to convert a specified string to a String type and also check the presence of ASCII data. If the non-ASCII byte is present, throw an ArgumentError indicating the position of the first non-ASCII byte. Syntax: ascii(s::AbstractString) Parameters:s::AbstractString: Specified stringReturns: It r
1 min read
Subsequences generated by including characters or ASCII value of characters of given string
Given a string str of length N, the task is to print all possible non-empty subsequences of the given string such that the subsequences either contain characters or ASCII values of the characters from the given string. Examples: Input: str = "ab" Output: b 98 a ab a98 97 97b 9798 Explanation: Possible subsequence of the strings are { b, a, ab }. Po
6 min read
Substring with maximum ASCII sum when some ASCII values are redefined
Given a string W, and two arrays X[] and B[] of size N each where the ASCII value of character X[i] is redefined to B[i]. Find the substring with the maximum sum of the ASCII (American Standard Code for Information Interchange) value of the characters. Note: Uppercase &amp; lowercase both will be present in the string W. Input: W = "abcde", N = 1,
9 min read
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Count characters in a string whose ASCII values are prime
Given a string S. The task is to count and print the number of characters in the string whose ASCII values are prime. Examples: Input: S = "geeksforgeeks" Output : 3 'g', 'e' and 'k' are the only characters whose ASCII values are prime i.e. 103, 101 and 107 respectively. Input: S = "abcdefghijklmnopqrstuvwxyz" Output: 6 Approach: The idea is to gen
6 min read