Char Profile
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L3
Problem
Given a string, return a dict mapping each distinct character to its count.
Every character in the string tells a story.
Example 1
Input:
s = "hello"
Output:
{"h":1,"e":1,"l":2,"o":1}Example 2
Input:
s = ""
Output:
{}Worked solution and explanation
Why this problem exists in real interviews
Building a character frequency map is the simplest form of histogram construction in Python. It tests dict manipulation, iteration, and whether you handle the first-occurrence case cleanly.
Break down the requirements
Step 1: Iterate through each character
Visit every character in the string, including spaces, digits, and special characters.
Step 2: Accumulate counts in a dictionary
For each character, increment its count or initialize it to 1 if not yet seen.
The solution
def char_freq(s):
counts = {}
for char in s:
if char not in counts:
counts[char] = 0
counts[char] += 1
return countsCommon follow-up questions
- How would you ignore case when counting? (Tests whether you normalize with `.lower()` before counting.)
- What if you needed the top-k most frequent characters? (Tests sorting a dict by value and taking a slice.)
- How does collections.Counter compare to a manual approach? (Tests knowledge of stdlib: Counter is a dict subclass with `most_common()` built in.)