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

Character frequency map via single-pass accumulation
def char_freq(s):
    counts = {}
    for char in s:
        if char not in counts:
            counts[char] = 0
        counts[char] += 1
    return counts

Common follow-up questions