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:

  1. Create a frequency map to count each character occurrence
  2. Convert the map to an array of [character, frequency] pairs
  3. Sort the array by frequency in descending order
  4. 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.

Updated on: 2026-03-15T23:18:59+05:30

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements