Open In App

Count of lexicographically smaller characters on right

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Examples: 

Input: str = “edcba” 
Output: 4 3 2 1 0 
Explanation: 
The number of characters on the right side of index 0 which is smaller than 
e are dcba = 4 
The number of characters on the right side of index 1 which is smaller than 
d are cba = 3 
The number of characters on the right side of index 2 which is smaller than 
c are ba = 2 
The number of characters on the right side of index 3 which is smaller than 
b are a = 1 
The 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  

Naive Approach: 
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 that are alphabetically smaller.

C++




#include <bits/stdc++.h>
using namespace std;
 
// function to count the smaller
// characters at the right of index i
void countSmaller(string str)
{
 
    // store the length of string
    int n = str.length();
    for (int i = 0; i < n; i++) {
 
        // for each index initialize
        // count as zero
        int cnt = 0;
        for (int j = i + 1; j < n; j++) {
 
            // increment the count if
            // characters are smaller
            // than at ith index
            if (str[j] < str[i]) {
                cnt += 1;
            }
        }
 
        // print the count of characters
        // smaller than the index i
        cout << cnt << " ";
    }
}
 
// Driver code
int main()
{
    // input string
    string str = "edcba";
    countSmaller(str);
}


Java




class GFG
{
 
// function to count the smaller
// characters at the right of index i
static void countSmaller(String str)
{
 
    // store the length of String
    int n = str.length();
    for (int i = 0; i < n; i++)
    {
 
        // for each index initialize
        // count as zero
        int cnt = 0;
        for (int j = i + 1; j < n; j++)
        {
 
            // increment the count if
            // characters are smaller
            // than at ith index
            if (str.charAt(j) < str.charAt(i))
            {
                cnt += 1;
            }
        }
 
        // print the count of characters
        // smaller than the index i
        System.out.print(cnt+ " ");
    }
}
 
// Driver code
public static void main(String[] args)
{
    // input String
    String str = "edcba";
    countSmaller(str);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# function to count the smaller
# characters at the right of index i
def countSmaller(str):
 
    # store the length of String
    n = len(str);
    for i in range(n):
 
        # for each index initialize
        # count as zero
        cnt = 0;
        for j in range(i + 1, n):
 
            # increment the count if
            # characters are smaller
            # than at ith index
            if (str[j] < str[i]):
                cnt += 1;
             
        # print the count of characters
        # smaller than the index i
        print(cnt, end =" ");
     
# Driver code
if __name__ == '__main__':
 
    # input String
    str = "edcba";
    countSmaller(str);
 
# This code is contributed by PrinciRaj1992


C#




using System;
 
class GFG
{
 
// function to count the smaller
// characters at the right of index i
static void countSmaller(String str)
{
 
    // store the length of String
    int n = str.Length;
    for (int i = 0; i < n; i++)
    {
 
        // for each index initialize
        // count as zero
        int cnt = 0;
        for (int j = i + 1; j < n; j++)
        {
 
            // increment the count if
            // characters are smaller
            // than at ith index
            if (str[j] < str[i])
            {
                cnt += 1;
            }
        }
 
        // print the count of characters
        // smaller than the index i
        Console.Write(cnt+ " ");
    }
}
 
// Driver code
public static void Main(String[] args)
{
    // input String
    String str = "edcba";
    countSmaller(str);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
 
// function to count the smaller
// characters at the right of index i
function countSmaller(str)
{
 
    // store the length of string
    var n = str.length;
    for (var i = 0; i < n; i++) {
 
        // for each index initialize
        // count as zero
        var cnt = 0;
        for (var j = i + 1; j < n; j++) {
 
            // increment the count if
            // characters are smaller
            // than at ith index
            if (str[j] < str[i]) {
                cnt += 1;
            }
        }
 
        // print the count of characters
        // smaller than the index i
        document.write( cnt + " ");
    }
}
 
// Driver code
// input string
var str = "edcba";
countSmaller(str);
 
 
 
</script>


Output: 

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 the size of the subtree rooted with N. We have used the 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 the root. If the key is greater than the root, then it is greater than all the nodes in the left subtree of the 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 the implementation of the above approach.
Time Complexity: O(N*log N
Auxiliary Space: O(N)
 

Efficient Approach: 
The idea is to use hashing techniques because the 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 the right and keep updating the count of characters in the hash array. Now, to find the count of smaller characters on the right, we can simply traverse the hash array of size 26 every time to count smaller characters encountered so far.  

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to count the smaller
// characters on the right of index i
void countSmaller(string str)
{
    // store the length of string
    int n = str.length();
 
    // initialize each elements of
    // arr to zero
    int arr[26] = { 0 };
 
    // array to store count of smaller characters on
    // the right side of that index
    int ans[n];
 
    for (int i = n - 1; i >= 0; i--) {
 
        arr[str[i] - 'a']++;
 
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        int ct = 0;
 
        // adding the count of characters
        // smaller than index i
        for (int j = 0; j < str[i] - 'a'; j++) {
            ct += arr[j];
        }
        ans[i] = ct;
    }
 
    // print the count of characters smaller
    // than index i stored in ans array
    for (int i = 0; i < n; i++) {
        cout << ans[i] << " ";
    }
}
 
// Driver Code
int main()
{
    string str = "edcbaa";
    countSmaller(str);
 
    return 0;
}


Java




class GFG
{
 
// Function to count the smaller
// characters on the right of index i
static void countSmaller(String str)
{
    // store the length of String
    int n = str.length();
 
    // initialize each elements of
    // arr to zero
    int arr[] = new int[26];
 
    // array to store count of smaller characters on
    // the right side of that index
    int ans[] = new int[n];
 
    for (int i = n - 1; i >= 0; i--)
    {
 
        arr[str.charAt(i) - 'a']++;
 
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        int ct = 0;
 
        // adding the count of characters
        // smaller than index i
        for (int j = 0; j < str.charAt(i) - 'a'; j++)
        {
            ct += arr[j];
        }
        ans[i] = ct;
    }
 
    // print the count of characters smaller
    // than index i stored in ans array
    for (int i = 0; i < n; i++)
    {
        System.out.print(ans[i] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "edcbaa";
    countSmaller(str);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Function to count the smaller
# characters on the right of index i
def countSmaller(str):
 
    # store the length of String
    n = len(str);
 
    # initialize each elements of
    # arr to zero
    arr = [0]*26;
 
    # array to store count of smaller characters on
    # the right side of that index
    ans = [0]*n;
 
    for i in range(n - 1, -1, -1):
 
        arr[ord(str[i] ) - ord('a')] += 1;
 
        # initialize the variable to store
        # the count of characters smaller
        # than that at index i
        ct = 0;
 
        # adding the count of characters
        # smaller than index i
        for j in range(ord(str[i] ) - ord('a')):
            ct += arr[j];
         
        ans[i] = ct;
     
    # print the count of characters smaller
    # than index i stored in ans array
    for i in range(n):
        print(ans[i], end = " ");
     
# Driver Code
if __name__ == '__main__':
    str = "edcbaa";
    countSmaller(str);
     
# This code is contributed by Rajput-Ji


C#




using System;
 
class GFG
{
 
// Function to count the smaller
// characters on the right of index i
static void countSmaller(String str)
{
    // store the length of String
    int n = str.Length;
 
    // initialize each elements of
    // arr to zero
    int []arr = new int[26];
 
    // array to store count of smaller characters on
    // the right side of that index
    int []ans = new int[n];
 
    for (int i = n - 1; i >= 0; i--)
    {
 
        arr[str[i] - 'a']++;
 
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        int ct = 0;
 
        // adding the count of characters
        // smaller than index i
        for (int j = 0; j < str[i] - 'a'; j++)
        {
            ct += arr[j];
        }
        ans[i] = ct;
    }
 
    // print the count of characters smaller
    // than index i stored in ans array
    for (int i = 0; i < n; i++)
    {
        Console.Write(ans[i] + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "edcbaa";
    countSmaller(str);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
 
// Function to count the smaller
// characters on the right of index i
function countSmaller(str)
{
    // store the length of string
    var n = str.length;
 
    // initialize each elements of
    // arr to zero
    var arr = Array(26).fill(0);
 
    // array to store count of smaller characters on
    // the right side of that index
    var ans = Array(n);
 
    for (var i = n - 1; i >= 0; i--) {
 
        arr[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
 
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        var ct = 0;
 
        // adding the count of characters
        // smaller than index i
        for (var j = 0; j < str[i].charCodeAt(0) - 'a'.charCodeAt(0); j++) {
            ct += arr[j];
        }
        ans[i] = ct;
    }
 
    // print the count of characters smaller
    // than index i stored in ans array
    for (var i = 0; i < n; i++) {
        document.write( ans[i] + " ");
    }
}
 
// Driver Code
var str = "edcbaa";
countSmaller(str);
 
</script>


Output: 

5 4 3 2 0 0

 

Time Complexity: O(N*26) 
Auxiliary Space: O(N+26)
 



Last Updated : 28 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads