Character Frequency Counter - Problem

Given a string, find the frequency of each character and display the results in descending order of frequency.

If two characters have the same frequency, they can appear in any order relative to each other.

Input: A single string containing letters, numbers, and special characters

Output: A string showing each character and its frequency, sorted by frequency in descending order

Format: Each character-frequency pair should be displayed as "character:frequency", separated by commas

Input & Output

Example 1 — Basic Case
$ Input: s = "hello"
Output: l:2,h:1,e:1,o:1
💡 Note: Character frequencies: h→1, e→1, l→2, o→1. Sorted by frequency descending: l appears 2 times (highest), then h, e, o each appear 1 time
Example 2 — Mixed Characters
$ Input: s = "aabbcc"
Output: a:2,b:2,c:2
💡 Note: All characters have same frequency (2), so they can appear in any order relative to each other
Example 3 — Single Character
$ Input: s = "aaaa"
Output: a:4
💡 Note: Only one unique character 'a' appears 4 times

Constraints

  • 1 ≤ s.length ≤ 1000
  • s contains only printable ASCII characters

Visualization

Tap to expand
INPUT STRINGALGORITHMRESULThelloString: "hello"1Count frequenciesBuild hash map2Sort by frequencyDescending order3Format outputchar:freq pairsFrequency Maph: 1, e: 1l: 2, o: 1l highest (2)l:2,h:1,e:1,o:1Sorted by frequency✓ 'l' appears most (2 times)✓ Others appear once eachKey Insight:Use hash map to count frequencies in one pass (O(n)), then sort uniquecharacters by their counts (O(k log k)) - much faster than counting each character separatelyTutorialsPoint - Character Frequency Counter | Hash Map Approach
Asked in
Google 25 Amazon 20 Microsoft 15 Apple 10
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen