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".
Table of Content
[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.
#include <iostream>
#include <algorithm>
using namespace std;
string sortString(string &s)
{
// Sort all characters in ascending order.
sort(s.begin(), s.end());
return s;
}
// Driver Code
int main()
{
string s = "xzy";
cout << sortString(s);
return 0;
}
import java.util.Arrays;
public class GfG {
// Sort all characters in ascending order.
static String sortString(String s)
{
char[] charArray = s.toCharArray();
Arrays.sort(charArray);
return new String(charArray);
}
// Driver Code
public static void main(String[] args)
{
String s = "xzy";
System.out.println(sortString(s));
}
}
"""
Sort all characters in ascending order.
"""
def sortString(s):
# Sort all characters in ascending order.
return ''.join(sorted(s))
# Driver Code
if __name__ == "__main__":
s = "xzy"
print(sortString(s))
using System;
class GfG {
public string sortString(string s)
{
char[] charArray = s.ToCharArray();
Array.Sort(charArray);
return new string(charArray);
}
public static int Main()
{
string s = "xzy";
GfG obj = new GfG();
Console.WriteLine(obj.sortString(s));
return 0;
}
}
// Sort all characters in ascending order.
function sortString(s) {
return s.split('').sort().join('');
}
// Driver Code
let s = "xzy";
console.log(sortString(s));
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.
#include <iostream>
#include <vector>
using namespace std;
string sortString(string &s)
{
vector<int> freq(26, 0);
// count frequency
for (char ch : s)
{
freq[ch - 'a']++;
}
string ans = "";
// rebuild in sorted order
for (int i = 0; i < 26; i++)
{
while (freq[i] > 0)
{
ans += (char)(i + 'a');
freq[i]--;
}
}
return ans;
}
// Driver Code
int main()
{
string s = "xzy";
cout << sortString(s);
return 0;
}
import java.util.*;
public class GfG {
public static String sortString(String s)
{
int[] freq = new int[26];
// count frequency
for (char ch : s.toCharArray()) {
freq[ch - 'a']++;
}
StringBuilder ans = new StringBuilder();
// rebuild in sorted order
for (int i = 0; i < 26; i++) {
while (freq[i] > 0) {
ans.append((char)(i + 'a'));
freq[i]--;
}
}
return ans.toString();
}
// Driver Code
public static void main(String[] args)
{
String s = "xzy";
System.out.println(sortString(s));
}
}
def sortString(s):
freq = [0] * 26
# count frequency
for ch in s:
freq[ord(ch) - ord('a')] += 1
ans = ""
# rebuild in sorted order
for i in range(26):
while freq[i] > 0:
ans += chr(i + ord('a'))
freq[i] -= 1
return ans
# Driver Code
if __name__ == "__main__":
s = "xzy"
print(sortString(s))
using System;
using System.Text;
class GfG {
public string sortString(string s)
{
int[] freq = new int[26];
foreach(char ch in s) { freq[ch - 'a']++; }
StringBuilder ans = new StringBuilder();
for (int i = 0; i < 26; i++) {
while (freq[i] > 0) {
ans.Append((char)(i + 'a'));
freq[i]--;
}
}
return ans.ToString();
}
public static void Main()
{
string s = "xzy";
GfG obj = new GfG();
Console.WriteLine(obj.sortString(s));
}
}
function sortString(s)
{
const freq = new Array(26).fill(0);
// count frequency
for (let ch of s) {
freq[ch.charCodeAt(0) - "a".charCodeAt(0)]++;
}
let ans = [];
// rebuild in sorted order
for (let i = 0; i < 26; i++) {
while (freq[i] > 0) {
ans.push(
String.fromCharCode(i + "a".charCodeAt(0)));
freq[i]--;
}
}
return ans.join("");
}
// Driver Code
let s = "xzy";
console.log(sortString(s));
Output
xyz
Time Complexity: O(n)
Auxiliary Space: O(1)