
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
Editorial
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. |
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