# Char Profile

> Every character in the string tells a story.

Canonical URL: <https://datadriven.io/problems/char_profile>

Domain: Python · Difficulty: medium · Seniority: L3

## Problem

Given a string, return a dict mapping each distinct character to its count.

## 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**

```python
def char_freq(s):
    counts = {}
    for char in s:
        if char not in counts:
            counts[char] = 0
        counts[char] += 1
    return counts
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the string length. Each character is visited once.
> 
> **Space:** O(k) where k is the number of unique characters.

> **Interviewers Watch For**
>
> Clean dict accumulation without importing Counter. This is a fundamentals check; reaching for `collections.Counter` is fine in production but interviewers want to see you can write the loop.

> **Common Pitfall**
>
> Using `counts[char] += 1` without checking if the key exists first. This raises a KeyError. Use `counts.get(char, 0) + 1` or an explicit check.

---

## Common 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.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/char_profile)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.