Advertisement
satishfrontenddev4

Untitled

Jan 6th, 2024
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. A string S is given consisting of lowercase alphabetical characters only. You need to return a sorted string using Count Sort.
  3.  
  4. Input format
  5. First line will contain a single integer n representing size of the given string.
  6.  
  7. Second line will contain a single string S of size n.
  8.  
  9. Output format
  10. Output the string in a single line.
  11.  
  12. Sample Input 1
  13. 10
  14.  
  15. abcdeedcba
  16.  
  17. Sample Output 1
  18. aabbccddee
  19.  
  20. Constraints
  21. 1<=n<=10^6
  22.  
  23. String S will contain lowercase alphabetical characters only
  24. */
  25.  
  26. /**
  27.  * @param {number} n
  28.  * @param {string} s
  29.  * @return {string}
  30.  */
  31. function countSort(n, str) {
  32.   let frequencyCount = new Array(26).fill(0);
  33.   for (let i = 0; i < n; i++) {
  34.     const charCode = str.charCodeAt(i) - "a".charCodeAt(0);
  35.     frequencyCount[charCode]++;
  36.   }
  37.   let sortedString = "";
  38.   for (let i = 0; i < 26; i++) {
  39.     for (let j = 0; j < frequencyCount[i]; j++) {
  40.       sortedString = sortedString + String.fromCharCode("a".charCodeAt(0) + i);
  41.     }
  42.   }
  43.   return sortedString;
  44. }
  45.  
  46. function main() {
  47.     let n = parseInt(readLine());
  48.     let str = readLine();
  49.  
  50.     let storedString = countSort(n, str);
  51.     print(storedString)
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement