Number of Larger Elements on right side in a string in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the number of larger element on right side in a string.

Let's see the steps to solve the problem.

  • Initialise the string.

  • Initialise an array to keep track of the count.

  • Write two loops to iterate over the string.

    • Take one char at a time and compare it with all the character after it.

    • Increment the corresponding character count in the count array if the current element is less than the next element.

  • Print the count of all characters.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void countCharNextLargerElementsCount(string str) {
   int len = str.length(), count[len];
   for (int i = 0; i < len; i++) {
      count[i] = 0;
   }
   for (int i = 0; i < len; i++) {
      for (int j = i + 1; j < len; j++) {
         if (str[i] < str[j]) {
            count[i]++;
         }
      }
   }
   for (int i = 0; i < len; i++) {
      cout << count[i] << " ";
   }
   cout << endl;
}
int main() {
   string str = "abcdefgh";
   countCharNextLargerElementsCount(str);
   return 0;
}

Output

If you run the above code, then you will get the following result.

7 6 5 4 3 2 1 0

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 03-Jul-2021 08:06:11
Advertisements