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
Selected Reading
Returning the second most frequent character from a string (including spaces) - JavaScript
We are required to write a JavaScript function that takes in a string and returns the character which makes second most appearances in the string.
Approach
The solution involves counting character frequencies, sorting them by frequency, and returning the second most frequent character. Here's how it works:
- Create a frequency map to count each character occurrence
- Convert the map to an array of [character, frequency] pairs
- Sort the array by frequency in descending order
- Return the character at index 1 (second position)
Example
Following is the code −
const str = 'Hello world, I have never seen such a beautiful weather in the world';
const secondFrequent = str => {
const map = {};
// Count frequency of each character
for(let i = 0; i [el, map[el]]);
// Sort by frequency in descending order
freqArr.sort((a, b) => b[1] - a[1]);
// Return second most frequent character
return freqArr[1][0];
};
console.log(secondFrequent(str));
Output
e
How It Works
Let's trace through the execution:
const str = 'Hello world';
const map = {};
// After counting frequencies
for(let i = 0; i [el, map[el]]);
freqArr.sort((a, b) => b[1] - a[1]);
console.log("Sorted by frequency:", freqArr);
console.log("Second most frequent:", freqArr[1][0]);
{ H: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
Sorted by frequency: [ [ 'l', 3 ], [ 'o', 2 ], [ 'H', 1 ], [ 'e', 1 ], [ ' ', 1 ], [ 'w', 1 ], [ 'r', 1 ], [ 'd', 1 ] ]
Second most frequent: o
Edge Cases
Consider handling edge cases like strings with fewer than 2 unique characters:
const secondFrequentSafe = str => {
const map = {};
for(let i = 0; i [el, map[el]]);
freqArr.sort((a, b) => b[1] - a[1]);
return freqArr.length >= 2 ? freqArr[1][0] : null;
};
console.log(secondFrequentSafe("aaa")); // null - only one unique character
console.log(secondFrequentSafe("Hello")); // 'l' - second most frequent
null l
Conclusion
This approach efficiently finds the second most frequent character by using a frequency map and sorting. The time complexity is O(n log n) due to sorting, where n is the number of unique characters.
Advertisements
