Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sorting string characters by frequency in JavaScript
In JavaScript, sorting string characters by frequency involves counting each character's occurrences and rearranging them from most frequent to least frequent. This technique is useful for data analysis, compression algorithms, and text processing tasks.
Problem Statement
We need to create a JavaScript function that takes a string as input and returns a new string where characters are arranged by their frequency in descending order. Characters appearing most frequently come first, followed by less frequent ones.
For example, if the input string is:
const str = 'free';
The expected output should be:
const output = 'eefr';
Here, 'e' appears twice, so it comes first, followed by 'f' and 'r' which appear once each.
Solution Approach
The solution involves three main steps:
- Count the frequency of each character using a hash map
- Sort characters by their frequency in descending order
- Reconstruct the string based on sorted frequencies
Implementation
const str = 'free';
const frequencySort = (str = '') => {
// Step 1: Count character frequencies
let map = {};
for (const letter of str) {
map[letter] = (map[letter] || 0) + 1;
}
// Step 2: Sort characters by frequency (descending)
let sorted = Object.keys(map).sort((a, b) => map[b] - map[a]);
// Step 3: Build result string
let result = "";
for (let letter of sorted) {
for (let count = 0; count < map[letter]; count++) {
result += letter;
}
}
return result;
};
console.log(frequencySort(str));
console.log(frequencySort('programming'));
console.log(frequencySort('aabbcc'));
eefr rrggmmaaipno aabbcc
How It Works
Step 1 - Frequency Counting: We iterate through each character and maintain a count in the `map` object. The expression `(map[letter] || 0) + 1` handles both new characters (defaulting to 0) and existing ones.
Step 2 - Sorting: We use `Object.keys(map).sort()` with a custom comparator `(a, b) => map[b] - map[a]` to sort characters by frequency in descending order.
Step 3 - String Reconstruction: For each sorted character, we append it to the result string as many times as its frequency count.
Alternative Implementation Using Array Methods
const frequencySortAlternative = (str = '') => {
const freqMap = {};
// Count frequencies
[...str].forEach(char => freqMap[char] = (freqMap[char] || 0) + 1);
// Sort and build result
return Object.entries(freqMap)
.sort(([,a], [,b]) => b - a)
.map(([char, freq]) => char.repeat(freq))
.join('');
};
console.log(frequencySortAlternative('programming'));
rrggmmaaipno
Time and Space Complexity
Time Complexity: O(n + k log k), where n is the string length and k is the number of unique characters. The counting takes O(n), sorting takes O(k log k), and reconstruction takes O(n).
Space Complexity: O(k) for storing the frequency map, where k is the number of unique characters.
Conclusion
Sorting characters by frequency is efficiently achieved by counting occurrences, sorting by frequency, and reconstructing the string. This approach maintains optimal performance while providing a clean, readable solution for text processing tasks.
