C++ Program to find length of substring song from main song

Suppose we have a string S with n characters and two values l and r. Amal has written song and shared it to Bimal. The song is a string consisting of lowercase English letters. Bimal made up a question about this song. The question is about a subsegment of the song starting from the index l to r. Bimal considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. As an example, if the question is about the substring "abbcb", then Bimal repeats letter 'a' once, each of the letters 'b' twice, letter 'c" thrice, so that the resulting string is "abbbbcccbb", and its length is 10. Bimal is interested about the length of the resulting string. We have to find that length.

Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the datatype for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.



So, if the input of our problem is like S = "abacaba"; l = 1; r = 3, then the output will be 4, because the substring "aba" is taken by Bimal, that transforms to "abba", so the answer is 4.


To solve this, we will follow these steps −

sum := 0
Define an array a of size: 100009.
sum := 0
n := size of S
for initialize i := 1, when i <= n, update (increase i by 1), do:
   x := S[i - 1]
   sum := sum + (x - ASCII of 'a' + 1)
   a[i] := sum
return a[r] - a[l - 1]


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(string S, int l, int r){
   int sum = 0;
   int a[100009];
   char x;
   sum = 0;
   int n = S.size();
   for (int i = 1; i <= n; i++){
      x = S[i - 1];
      sum += (x - 'a' + 1);
      a[i] = sum;
   return a[r] - a[l - 1];
int main(){
   string S = "abacaba";
   int l = 1;
   int r = 3;
   cout << solve(S, l, r) << endl;


"abacaba", 1, 3



Updated on: 08-Apr-2022


Kickstart Your Career

Get certified by completing the course

Get Started