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



Given a string, we have to count the number of larger elements on right side of each character. Let's see an example.

Input

string = "abc"

Output

2 1 0

There are 2 larger elements than a on its right side.

There is 1 larger element than b on its right side.

There are 0 larger elements than c on its right side.

Algorithm

  • 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.

Implementation

Following is the implementation of the above algorithm in C++

Implementation

Following is the implementation of the above algorithm in C++

#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

Updated on: 2021-10-26T14:45:24+05:30

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements