2026-07-12 20:56:17 -04:00
|
|
|
---
|
|
|
|
|
title: LC-451
|
|
|
|
|
description: Sort Characters By Frequency
|
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
## Examples
|
|
|
|
|
|
|
|
|
|
| Input | Output |
|
|
|
|
|
| ---------- | -------- |
|
|
|
|
|
| `"tree"` | `"eert"` |
|
|
|
|
|
| `"cccaaa"` | `"aaaccc"` |
|
|
|
|
|
| `"Aabb"` | `"bbAa"` |
|
|
|
|
|
|
|
|
|
|
## Hints
|
|
|
|
|
|
2026-07-14 11:10:30 -04:00
|
|
|
<Accordion type="single">
|
|
|
|
|
<AccordionItem title="Constraints">
|
2026-07-12 20:56:17 -04:00
|
|
|
Constraints:
|
|
|
|
|
• `1 <= s.length <= 5 * 10^5`
|
|
|
|
|
• `s` consists of uppercase and lowercase English letters and digits.
|
2026-07-14 11:10:30 -04:00
|
|
|
</AccordionItem >
|
|
|
|
|
<AccordionItem title="Problem Statement">
|
2026-07-12 20:56:17 -04:00
|
|
|
Given a string `s`, sort it in decreasing order based on the frequency of the characters.
|
|
|
|
|
The frequency of a character is the number of times it appears in the string.
|
|
|
|
|
Return the sorted string. If there are multiple answers, return any of them.
|
2026-07-14 11:10:30 -04:00
|
|
|
</AccordionItem >
|
|
|
|
|
</Accordion>
|
2026-07-12 20:56:17 -04:00
|
|
|
|
|
|
|
|
## Solution
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
/**
|
|
|
|
|
* @param {string} s
|
|
|
|
|
* @return {string}
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
var frequencySort = function (s) {
|
|
|
|
|
// Default for Hammer
|
|
|
|
|
const freq = {};
|
|
|
|
|
for (let c of s) freq[c] = (freq[c] || 0) + 1;
|
|
|
|
|
|
|
|
|
|
// Problem Specific
|
|
|
|
|
// Sort characters by descending frequency; same chars stay grouped
|
|
|
|
|
return s
|
|
|
|
|
.split("")
|
|
|
|
|
.sort((a, b) => freq[b] - freq[a] || a.localeCompare(b))
|
|
|
|
|
.join("");
|
|
|
|
|
};
|
|
|
|
|
```
|