Last Updated: 13 Apr, 2022

String Sort

Easy
Asked in companies
HCL TechnologiesChegg Inc.

Problem statement

You are given a string ‘S’ consisting of lowercase English alphabets from ‘a’ to ‘z’. You have to print the string in sorted order.

Input Format :
The first line of the input contains a single integer 'T', representing the number of test cases.

The first line of each test case contains a string ‘S’ denoting a string.
Example :
S = ‘bbccdefbbaa’

We sort the string lexicographically or in dictionary order.

Output is: ‘aabbbbccdef’.
Output format :
For each test case, output the sorted string.

Print the output of each test case in a new line.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10 
1 <= S.length <= 10^5
‘a’ <= S[i] <= ‘z’

Time Limit: 1 sec

Approaches

01 Approach

Use Inbuilt sort function.

02 Approach

  1. Hash the count of characters in the string in a hashmap/ array.
  2. Iterate from the ‘a’ to ‘z’ character in the hashmap and add the character the number of times its frequency in the result. 
     

The steps are as follows : 

  1. Create an array hash of length 26.
  2. For each character in string ‘s’
    • Increment the value of s[i] - ‘a’ in hash.
  3. Clear the string s’ to avoid extra space
    • iterate through 1 to 26
      • Add the character value of (‘a’+i), hash[i] number of times in s.