Sunday, January 12, 2025
Google search engine
HomeData Modelling & AISplit a given string into substrings of length K with equal sum...

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 = 5 
Output : NO 
Explanation : 
5 length substrings {“ababc”, “dabas”} with sum of their ASCII values equal to 507. 
 

 

Approach: 
Follow the steps below to solve the problem: 
 

  1. Check if N is divisible by K or not. If N is not divisible by K then it is not possible for all substrings to be of length K.
  2. Compute ASCII sum of all substrings of length K. If only a single sum is generated for all substrings, print “YES”.
  3. Otherwise, print “NO”.

Below is the implementation of the above approach : 
 

C++




// C++ program to check if a given
// string can be split into substrings
// of size K having an equal sum of
// ASCII values.
#include <bits/stdc++.h>
using namespace std;
 
// Function for checking string
bool check(string str, int K)
{
    // Check if the string can
    // be split into substrings
    // of K length only
    if (str.size() % K == 0) {
        int sum = 0, i;
 
        // Compute the sum of first
        // substring of length K
        for (i = 0; i < K; i++) {
            sum += str[i];
        }
        // Compute the sum of
        // remaining substrings
        for (int j = i; j < str.size();
             j += K) {
            int s_comp = 0;
            for (int p = j; p < j + K;
                 p++)
                s_comp += str[p];
            // Check if sum is equal
            // to that of the first
            // substring
            if (s_comp != sum)
                // Since all sums are not
                // equal, return false
                return false;
        }
        // All sums are equal,
        // Return true
        return true;
    }
    // All substrings cannot
    // be of size K
    return false;
}
// Driver Program
int main()
{
 
    int K = 3;
    string str = "abdcbbdba";
 
    if (check(str, K))
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
}


Java




// Java program to check if a given
// string can be split into substrings
// of size K having an equal sum of
// ASCII values.
class GFG{
 
// Function for checking string
static boolean check(String str, int K)
{
     
    // Check if the string can
    // be split into substrings
    // of K length only
    if (str.length() % K == 0)
    {
        int sum = 0, i;
 
        // Compute the sum of first
        // substring of length K
        for(i = 0; i < K; i++)
        {
           sum += str.charAt(i);
        }
         
        // Compute the sum of
        // remaining substrings
        for(int j = i; j < str.length(); j += K)
        {
           int s_comp = 0;
           for(int p = j; p < j + K; p++)
              s_comp += str.charAt(p);
               
           // Check if sum is equal
           // to that of the first
           // substring
           if (s_comp != sum)
                
               // Since all sums are not
               // equal, return false
               return false;
        }
         
        // All sums are equal,
        // Return true
        return true;
    }
     
    // All substrings cannot
    // be of size K
    return false;
}
 
// Driver code
public static void main(String args[])
{
    int K = 3;
    String str = "abdcbbdba";
 
    if (check(str, K))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by rock_cool


Python3




# Python3 program to check if a given
# string can be split into substrings
# of size K having an equal sum of
# ASCII values.
 
# Function for checking string
def check(str, K):
 
    # Check if the string can
    # be split into substrings
    # of K length only
    if (len(str) % K == 0):
        sum = 0
         
        # Compute the sum of first
        # substring of length K
        for i in range(K):
            sum += ord(str[i]);
         
        # Compute the sum of
        # remaining substrings
        for j in range(K, len(str), K):
            s_comp = 0;
            for p in range(j, j + K):
                s_comp += ord( str[p]);
                 
            # Check if sum is equal
            # to that of the first
            # substring
            if (s_comp != sum):
                 
                # Since all sums are not
                # equal, return False
                return False;
         
        # All sums are equal,
        # Return true
        return True;
     
    # All substrings cannot
    # be of size K
    return False;
 
# Driver code
K = 3;
str = "abdcbbdba";
 
if (check(str, K)):
    print("YES")
else:
    print("NO")
 
# This is code contributed by grand_master


C#




// C# program to check if a given
// string can be split into substrings
// of size K having an equal sum of
// ASCII values.
using System;
class GFG{
 
// Function for checking string
static bool check(string str, int K)
{
     
    // Check if the string can
    // be split into substrings
    // of K length only
    if (str.Length % K == 0)
    {
        int sum = 0, i;
 
        // Compute the sum of first
        // substring of length K
        for(i = 0; i < K; i++)
        {
            sum += str[i];
        }
         
        // Compute the sum of
        // remaining substrings
        for(int j = i; j < str.Length; j += K)
        {
            int s_comp = 0;
            for(int p = j; p < j + K; p++)
                s_comp += str[p];
                     
            // Check if sum is equal
            // to that of the first
            // substring
            if (s_comp != sum)
                     
                // Since all sums are not
                // equal, return false
                return false;
        }
         
        // All sums are equal,
        // Return true
        return true;
    }
     
    // All substrings cannot
    // be of size K
    return false;
}
 
// Driver code
public static void Main(string []args)
{
    int K = 3;
    string str = "abdcbbdba";
 
    if (check(str, K))
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by Ritik Bansal


Javascript




<script>
      // JavaScript program to check if a given
      // string can be split into substrings
      // of size K having an equal sum of
      // ASCII values.
      // Function for checking string
      function check(str, K) {
        // Check if the string can
        // be split into substrings
        // of K length only
        if (str.length % K === 0) {
          var sum = 0,
            i;
 
          // Compute the sum of first
          // substring of length K
          for (i = 0; i < K; i++) {
            sum += str[i].charCodeAt(0);
          }
 
          // Compute the sum of
          // remaining substrings
          for (var j = i; j < str.length; j += K) {
            var s_comp = 0;
            for (var p = j; p < j + K; p++) s_comp += str[p].charCodeAt(0);
 
            // Check if sum is equal
            // to that of the first
            // substring
            if (s_comp !== sum)
              // Since all sums are not
              // equal, return false
              return false;
          }
 
          // All sums are equal,
          // Return true
          return true;
        }
 
        // All substrings cannot
        // be of size K
        return false;
      }
 
      // Driver code
      var K = 3;
      var str = "abdcbbdba";
 
      if (check(str, K)) document.write("YES");
      else document.write("NO");
    </script>


Output: 

YES

 

Time Complexity: O (N) 
Auxiliary Space: O (1)
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments