mediumStringsPattern: Mixed

Character Frequency Sorting Solution

Problem Statement

Given a string `s`, find the frequency of each character and then reorder the string based on the frequency of characters in descending order. If two characters have the same frequency, the character with the smaller ASCII value will come first.

Examples

Example 1:
Input:tree
Output:eert
Explanation: Character frequencies: t-1, r-1, e-2. Reordered by frequency in descending order and then by ASCII value.
Example 2:
Input:hello
Output:llheo
Explanation: Character frequencies: h-1, e-1, l-2, o-1. Reordered by frequency in descending order and then by ASCII value.

Constraints

  • The length of the transmission message will not exceed 1000 characters.
  • The transmission message will only contain lowercase English letters.
Time: O(n log n) Space: O(n)
The optimized approach can be achieved using the built-in functions of JavaScript. First, count the frequency of each character using an object. Then, use the Object.entries() method to get an array of key-value pairs, sort the array based on the frequency and ASCII value using the Array.sort() method, and finally use the array.reduce() method to reconstruct the sorted string.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.