Skip to content
Related Articles

Related Articles

Count of lexicographically smaller characters on right
  • Difficulty Level : Easy
  • Last Updated : 28 Feb, 2020

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:
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

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 which 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
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 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)

Efficient Approach:
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.

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
Output:
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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :