VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-string-characters/

⇱ Sort string of characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort string of characters

Last Updated : 7 Jun, 2026

Given a string consisting of lowercase letters, arrange all its letters in ascending order.

Examples:

Input: s = "edcab"
Output: "abcde"
Explanation: characters are in ascending order in "abcde".

Input: s = "xzy"
Output: "xyz"
Explanation: characters are in ascending order in "xyz".

[Naive Approach] Using Built-in Sort - O(n log n) Time O(1) Space

The idea is to sort all characters of the string directly using built in sorting method. Since sorting arranges characters in ascending order, the resulting string becomes the required answer.


Output
xyz

Time Complexity: O(n log n)
Auxiliary Space: O(1)

[Expected Approach] Counting Frequency - O(n) Time O(1) Space

The idea is to count how many times each lowercase letter appears in the string. Since there are only 26 possible lowercase characters, we can store their frequencies and then rebuild the string from 'a' to 'z' according to those frequencies.

Let us understand with example:
Input: s = "xzy"

  • Create a frequency array freq of size 26 and initialize all values to 0.
  • Traverse the string and count frequencies: freq['x'-'a'] = 1, freq['z'-'a'] = 1, freq['y'-'a'] = 1.
  • Traverse freq from index 0 to 25 and append characters whose frequency is greater than 0.
  • Characters are added in the order 'x', 'y', 'z', so ans becomes "xyz".
  • Return "xyz" as the sorted string.

Output
xyz

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags: