Counting Sort | Practice | GeeksforGeeks

Given a string arr consisting of lowercase english letters, arrange all its letters in lexicographical order using Counting Sort.
Example 1:
Input:
N = 5
S = "edsab"
Output:
abdes
Explanation: 
In lexicographical order, string will be 
abdes.

Example 2:
Input:
N = 13
S = "geeksforgeeks"
Output:
eeeefggkkorss
Explanation:
In lexicographical order, string will be 
eeeefggkkorss.
Your Task:
This is a function problem. You only need to complete the function countSort() that takes string arr as a parameter and returns the sorted string. The printing is done by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ N ≤ 105

Video:
YouTubeGeeksforGeeks500K subscribersCounting Sort | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.Full screen is unavailable. Learn MoreMore videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:19•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7zuGmKfUt7s" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
0
mitradiptamoy2 weeks ago
 //order using Counting Sort.   string countSort(string arr){       // code here       int count[26]={0};       int len=arr.length();       char output[len];       for(int i=0;i<len;i++)       {           count[arr[i]-'a']++;       }       for(int i=1;i<26;i++)       {           count[i]+=count[i-1];       }      for(int i=len-1;i>=0;i--)      {          output[-- count[arr[i]-'a']]=arr[i];      }       for(int i=0;i<len;i++)       {           arr[i]=output[i];       }       return arr;   }
0
tarun119043124 weeks ago
C++ efficient of all
string countSort(string arr){
        int hash[26]={0};
        string res=arr;
        for(auto i:arr)
            hash[i-'a']++;
            
        for(int i=1;i<26;i++)
            hash[i] += hash[i-1];
            
        
        for(int i=0;i<arr.size();i++){
            
            res[hash[arr[i]-'a']-1]=arr[i];
            hash[arr[i]-'a']--;
        }
        
        return res;
    }
0
saikirannagarjuna0071 month ago
class Solution{   //Function to arrange all letters of a string in lexicographical    //order using Counting Sort.   public static String countSort(String arr)   {       // code here       StringBuilder sb=new StringBuilder();       char ch[]=arr.toCharArray();       Arrays.sort(ch);       for(int i=0;i<ch.length;i++){           sb.append(ch[i]);       }       return sb.toString();   }}
0
gunjangoyal2821 month ago
class Solution:
    #Function to arrange all letters of a string in lexicographical 
    #order using Counting Sort.
    def countSort(self,arr):
        # code here
        freq = [0]*26
        result = ""
        for i in range(len(arr)):
            idx = ord(arr[i]) - ord('a')
            freq[idx]+=1
        for i in range(len(freq)):
            value = freq[i]
            if value != 0:
                while value > 0:
                    idx = ord('a') + i
                    result+=chr(idx)
                    value-=1
        return result
0
gunjangoyal2821 month ago
class Solution{
    public:
    //Function to arrange all letters of a string in lexicographical 
    //order using Counting Sort.
    string countSort(string arr){
        // code here
        int freq[26];
        memset(freq,0,sizeof(freq));
        for(int i=0; i<arr.size(); i++){
            freq[arr[i]-'a']++;
        }
        string res = "";
        for(int i=0; i<26; i++){
            if(freq[i] != 0){
                int x = freq[i];
                while(x){
                    res+=char('a'+i);
                    x--;
                }
            }
        }
        return res;
    }
};
0
gunjangoyal2821 month ago
def countSort(self,arr):
        # code here
        res = ''.join(sorted(arr))
        return res
+2
ahmed072 months ago
class Solution{
   public:
   string countSort(string arr){
       int count[26] = {0};
       int l = arr.size();
       for(int i=0; i<l; i++)count[arr[i] - 'a']++;
       string ans = "";
       for(int i=0; i<26; i++){
           while(count[i]>0){
               ans += char(i + 'a');
               count[i]--;
           }
       }
       return ans;
   }
};
0
ashisbehera2 months ago
simple java sol
 
     int[] arr = new int[26];
        for(int i=0;i<s.length();i++){
            arr[s.charAt(i)-'a']++;
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<26;i++){
            if(arr[i]>0){
            int val = arr[i];
            while(val-->0){
                sb.append((char)(i+'a'));
             }
            }
        }
        return sb.toString();
+1
nkalyansaivarma2 months ago
C++ implementation here:
some changes to the normal counting sort algorithm makes it useful in case of strings.
string countSort(string arr){
        // code here
        int len = arr.length();
        int temp[26]={0};
        for(int i=0;i<len;i++)
        {
            temp[int(arr[i])-97]++;
        }
        for(int i=1;i<26;i++)
        {
            temp[i] = temp[i-1]+temp[i];
        }
        char output[len];
        for(int i = len-1;i>=0;i--)
        {
            output[temp[(int(arr[i])-97)]-1] = arr[i];
            temp[int(arr[i])-97]--;
        }
        for(int i=0;i<len;i++)
        {
            arr[i] = output[i];
        }
        return arr;
    }
0
aadijup2 months ago
JAVA code:
class Solution{   //Function to arrange all letters of a string in lexicographical    //order using Counting Sort.   public static String countSort(String arr)   {       // code here       int l = arr.length();       int count[] = new int[26];       for(int i=0;i<l;i++)           count[(arr.charAt(i) - 'a')]++;       for(int j=1;j<26;j++)           count[j] += count[j - 1];              char op[] = new char[l];       for(int k=0;k<l;k++)       {           op[count[arr.charAt(k) - 'a'] - 1] = (char)arr.charAt(k);           count[arr.charAt(k) - 'a']--;       }       return String.valueOf(op);   }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.