Count of all substrings with sum of weights at most K


Introduction

In this tutorial, we discuss the problem of counting the substrings from a given string with the sum of weights at most K. To implement the problem statement we consider a string S to generate substrings and some value for k. The character weights are predefined integer values and we consider some value of K like 2, 3 or anything. We count only those substrings whose total weight is equal to the value of K.

The weights of the characters are defined in two different ways −

  • When the weights are defined for a string in any order.

  • When the weights are defined in alphabetical order starting from 1.

Example 1

String = "aba"
K = 5

Output

The possible substrings with their weights at most 5 is : 6

Explanation

Using the input string and the value of k, we take the weights of the characters in alphabetical order starting with 1. The weight of 'a' is 1, 'b' is 2, 'c' is 3, 'd' is 4, and so on. There are 6 possible substrings with a sum of weights at most K. The substrings are as follows −

a
ab
aba
b
ba
a

Example 2

String = "abcd" 
Weight = "1234"
K = 6

Output

Number of substring with their weight at most 6 are 7.

Explanation

In the above input string, we initialize the weight of all characters. The value of k is 6. The weights of characters of the string "abcd" are 1234 respectively. There are 7 possible substrings with sum of weights at most k. Those substrings are as follows −

a
ab
ab
cb
bc
c
d

C++ Library Functions

  • length() − It is a string class library function, defined in the standard C++ library. It returns the length of the string in bytes.

string_name.length();
  • vector − It is a dynamic array in C++. It provides easy and efficient deletion and updation operations of the array. It can be of integer or string type.

vector<data_type> vector_name;
  • unordered_set() − It is a container in C++ that stores elements randomly without any defined order. It helps in fast retrieval of its stored elements.

unordered_set <data_type> unordered_set_name;

Algorithm

  • Initialize the input string.

  • Consider the weight of the characters in alphabetical order starting from 1.

  • Initialize the value of k(maximum possible weight).

  • Iterate through all substrings whose weight is at most equal to k.

  • The counter variable counts all substrings with weights at most k.

  • Print the result of the k.

Example 1

Here, we implement the problem statement using C++. The user-defined function "countSubstrings()" to count all substrings with sum of weights equals at most K . The substring weights start at 1 and are assigned alphabetically.

#include <iostream>
#include <string>

using namespace std;

int countSubstrings(const string& s, int K) {
   int cnt = 0;
   int l = s.length();
    
   for (int x = 0; x < l; x++){
      int sum = 0;
        
      for (int y = x; y < l; y++) {
         // Calculate the weight of the substring from index i to j
         sum += s[y] - 'a' + 1;  // Assuming weights are based on alphabetical order
         
         // If the sum of weights is less than or equal to K, increment the count
         if (sum <= K){
            cnt++;
         }
      }
   }
    
   return cnt;
}
int main() {
   string s = "aba";  // Predefined string
   int K = 5;  // Predefined maximum weight
   
   int Output = countSubstrings(s, K);
   cout << "Count of substrings with sum of weights at most " << K << ": " << Output << endl;
   
   // Generating substrings
   cout << "Substrings with sum of weights at most " << K << ":" << endl;
   int l = s.length();
   for (int x = 0; x < l; x++) {
      for (int y = x; y < l; y++){
         string substrg = s.substr(x, y - x + 1);
         int weight = 0;
         for (char ch : substrg){
            weight += ch - 'a' + 1;
         }
         if (weight <= K) {
            cout << substrg << endl;
         }
      }
   }
    
   return 0;
}

Output

Count of substrings with sum of weights at most 5: 6
Substrings with sum of weights at most 5:
a
ab
aba
b
ba
a

Example 2

We implement the task with C++. Initialize a string of characters and a weighted string. The weight string elements are applied as input string weights. Used nested loops to generate substrings using the weight string. Count the substrings with their sum of weights at most K.

#include <iostream>
#include <unordered_set>
using namespace std;

//user-defined function to generate the substrings
void generateSubstrings(string s, string weights, int K, unordered_set<string>& substrings){
   //taking length of the input string
   int l = s.length();

   //loop for generating all substrings
   for (int x = 0; x < l; x++){
      for (int y = 1; y <= l - x; y++) {
         string substring = s.substr(x, y);
     
         //Sum variable to calculate the weights
         int sumString = 0;
         for (char c : substring){
            int post = c - 'a';
            sumString += weights[post] - '0';
         }
         //when string sun is less than equal to K, insert the substring
         if (sumString <= K){
            substrings.insert(substring);
            cout << substring << endl;
         }
      }
   }
}

//Code controller
int main(){
   //initialize string
   string S = "abcd";

   //initialize weight variable
   string W = "1234";

   //initialize value of K
   int K = 6;

   unordered_set<string> substrings;

   //calling function
   generateSubstrings(S, W, K, substrings);

   cout << "Count of substrings with weights at most " << K << ": " << substrings.size() << endl;

   return 0;
}

Output

a
ab
abc
b
bc
c
d
Count of substrings with weights at most 6: 7

Conclusion

In this tutorial, we count all substrings with weights of at most k. We implemented the task using two different methods. In the first case, we used a weighted string to initialize the weights of the input string characters. In the second case, the weights are defined in alphabetical order starting at 1. C++ was used to implement both cases with nested loop concepts.

Demonstrated the problem with some examples before writing C++ code to understand the problem statement needs and count the substrings.

Updated on: 29-Sep-2023

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements