- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Replace Elements with Greatest Element on Right Side in C++
- Count smaller elements on right side using Set in C++ STL
- Finding the element larger than all elements on right - JavaScript
- Number of smaller and larger elements - JavaScript
- Binary Tree Right Side View in C++
- String Formatting in C# to add padding on the right
- Maximum difference between two elements such that larger element appears after the smaller number in C
- Return a subarray that contains all the element from the original array that are larger than all the elements on their right in JavaScript
- Why Indian Vehicles steering is on Left Side while few Foreign countries in right side?
- Unpack elements and set the unpack count larger than the available number of bits in Numpy
- Number of Segments in a String in C++
- Larger of a^b or b^a in C++
- How to split a string into elements of a string array in C#?
- Frequency of smaller and larger elements - JavaScript
- Maximum sum of a path in a Right Number Triangle in C++
