easyStringsPattern: Frequency Map

Character Frequency Counter Solution

Problem Statement

Given a string consisting of lowercase English letters, write a function to return a dictionary containing the frequency of each character in the string.

Examples

Example 1:
Input:hello
Output:{"h":1,"e":1,"l":2,"o":1}
Explanation: The character 'h' appears once, 'e' appears once, 'l' appears twice, and 'o' appears once in the input string 'hello'.
Example 2:
Input:abcabc
Output:{"a":2,"b":2,"c":2}
Explanation: All characters in the input string 'abcabc' appear twice.

Constraints

  • The length of the input string will not exceed 10^5 characters.
  • The input string will only contain lowercase English letters.
  • The function should return a dictionary where the keys are characters and the values are their frequencies in the string.
Time: O(n) Space: O(n)
A more efficient approach is to use a single pass through the string, utilizing a dictionary to store character frequencies. This approach has a time complexity of O(n), where n is the length of the string, making it much more efficient for large inputs.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.