-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountSort-GFGQ.cpp
More file actions
89 lines (71 loc) · 1.5 KB
/
CountSort-GFGQ.cpp
File metadata and controls
89 lines (71 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Counting Sort
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
*/
//{ Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
#define RANGE 255
// } Driver Code Ends
//User function Template for C++
class Solution{
public:
//Function to arrange all letters of a string in lexicographical
//order using Counting Sort.
string countSort(string arr){
// code here
vector<int>count(26, 0);
string res = "";
for (char ch : arr) count[ch - 'a']++;
int cnt = 0;
while (cnt < 26) {
while (count[cnt]--) {
res += (cnt + 'a');
}
cnt++;
}
return res;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
string arr;
cin>>arr;
Solution obj;
cout<<obj.countSort(arr)<<endl;
}
return 0;
}
// } Driver Code Ends