Given a string consisting of only lowercase English alphabets. The task is to count the total number of alphabetically smaller characters on the right side of characters at each index.
Input: str = “edcba”
Output: 4 3 2 1 0
Number of characters on the right side of index 0 which is smaller than
e are dcba = 4
Number of characters on the right side of index 1 which is smaller than
d are cba = 3
Number of characters on the right side of index 2 which is smaller than
c are ba = 2
Number of characters on the right side of index 3 which is smaller than
b are a = 1
Number of characters on the right side of index 4 which is smaller than
a are ‘\0’ = 0
Input: str = “eaaa”
Output: 3 0 0 0
The idea is to traverse all the characters on the right side of each index of string one by one and print the count of characters which are alphabetically smaller.
4 3 2 1 0
Time Complexity: O(N2), where N = length of string
Auxiliary Space: O(1)
Better Approach: The idea is to Use Self Balancing BST.
A Self Balancing Binary Search Tree (AVL, Red Black, .. etc) can be used to get the solution in O(N log N) time complexity. We can augment these trees so that every node N contains size the subtree rooted with N. We have used AVL tree in the following implementation.
We traverse the string from right to left and insert all elements one by one in an AVL tree. While inserting a new key in an AVL tree, we first compare the key with root. If the key is greater than root, then it is greater than all the nodes in the left subtree of root. So we add the size of the left subtree to the count of smaller elements for the key being inserted. We recursively follow the same approach for all nodes down the root.
Please refer to this article for implementation of above approach.
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
The idea is to use hashing technique because string consists of only lowercase alphabets. So here we can take an array of size 26 that is used to store the count of smaller characters on the right side of that index.
Traverse the array from right and keep updating the count of characters in the hash array. Now, to find the count of characters smaller on right, we can simply traverse the hash array of size 26 every time to count smaller characters encountered so far.
5 4 3 2 0 0
Time Complexity: O(N*26)
Auxiliary Space: O(N+26)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.