Rune Ledger: Character Frequency
๐ฆ Rune Ledger: Character Frequency
Difficulty: Beginner Tags: strings, hash-map, counting, dictionary Series: CS 101: Fundamentals
Problem
In the ancient library, scholars maintain a ledger of rune frequencies. Count how many times each character appears in the mystical text.
Given a string, return a dictionary mapping each character to its frequency (number of occurrences). The counting is case-sensitive.
Real-World Application
Character frequency counting appears in: - Text analysis - word clouds, sentiment analysis, stylometry - Cryptography - frequency analysis, cipher breaking - Compression algorithms - Huffman coding, LZ77 - Spam detection - analyzing character distributions - Anagram detection - comparing character frequencies - Data deduplication - identifying similar strings - Natural language processing - n-gram analysis - Search engines - term frequency calculations
Input
data = str # String to analyze
Output
dict[str, int] # Character โ frequency mapping
Constraints
- String length โค 100,000
- ASCII text (letters, digits, punctuation, spaces, etc.)
- Case-sensitive counting
Examples
Example 1: Basic Frequency Count
Input: "aba!"
Output: {'a': 2, 'b': 1, '!': 1}
Explanation: - 'a' appears 2 times - 'b' appears 1 time - '!' appears 1 time
Example 2: Empty String
Input: ""
Output: {}
Explanation: - No characters to count - Return empty dictionary
Example 3: Case Sensitivity
Input: "Aa"
Output: {'A': 1, 'a': 1}
Explanation: - 'A' and 'a' are different characters - Each counted separately
Example 4: Repeated Characters
Input: "aaaaaa"
Output: {'a': 6}
Explanation: - Only one unique character - Appears 6 times
Example 5: With Spaces and Punctuation
Input: "Hello, World!"
Output: {'H': 1, 'e': 1, 'l': 3, 'o': 2, ',': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1}
Explanation: - All characters counted including spaces and punctuation - 'l' appears 3 times, 'o' appears 2 times
What You'll Learn
- Building frequency tables with dictionaries
- Iterating over strings
- Using
get()method for safe dictionary access - Understanding hash maps for O(1) lookups
- Difference between mutable (dict) and immutable (string) types
Why This Matters
Character frequency counting is: - Fundamental pattern in programming - Building block for many algorithms - Interview favorite - tests hash map understanding - Practical skill used in real applications
Starter Code
def challenge_function(data):
"""
Count frequency of each character in string.
Args:
data: str to analyze
Returns:
dict[str, int]: character โ count mapping
"""
# Your implementation here
pass