Tutorialspoint
Problem
Solution
Submissions

Count the Frequency of Each Character in a String

Certification: Basic Level Accuracy: 73.91% Submissions: 46 Points: 10

Write a Python program that counts the frequency of each character in a string and returns a dictionary with characters as keys and their frequencies as values.

Example 1
  • Input: string = "hello"
  • Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
  • Explanation:
    • Step 1: Initialize an empty dictionary to store character frequencies.
    • Step 2: Iterate through each character in the input string "hello".
    • Step 3: For each character, if it's already in the dictionary, increment its count; otherwise, add it with a count of 1.
    • Step 4: Character 'h' appears once, 'e' appears once, 'l' appears twice, and 'o' appears once.
    • Step 5: Return the dictionary with characters and their frequencies.
Example 2
  • Input: string = "banana"
  • Output: {'b': 1, 'a': 3, 'n': 2}
  • Explanation:
    • Step 1: Initialize an empty dictionary to store character frequencies.
    • Step 2: Iterate through each character in the input string "banana".
    • Step 3: For each character, if it's already in the dictionary, increment its count; otherwise, add it with a count of 1.
    • Step 4: Character 'b' appears once, 'a' appears three times, and 'n' appears twice.
    • Step 5: Return the dictionary with characters and their frequencies.
Constraints
  • 1 ≤ len(string) ≤ 10^6
  • String contains printable ASCII characters
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(k) where k is the number of unique characters in the string
StringsFunctions / MethodsTech MahindraSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a dictionary to track frequency: Initialize an empty dictionary and increment count for each character
  • Use Counter from collections module: from collections import Counter; return Counter(s)
  • Use dictionary comprehension: {char: s.count(char) for char in set(s)}
  • Loop through the string once and populate the dictionary

Steps to solve by this approach:

 Step 1: Initialize an empty dictionary to store character frequencies.

 Step 2: Iterate through each character in the input string.
 Step 3: Check if the character exists in the dictionary.
 Step 4: If the character exists, increment its count; otherwise, add it with count 1.
 Step 5: Return the completed frequency dictionary.

Submitted Code :