# The Character Map

> Character-level frequency. As a dictionary.

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

Domain: Python · Difficulty: easy · Seniority: L6

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

This tests the most fundamental dict accumulation pattern in Python: iterating a sequence and counting occurrences. It reveals whether a candidate reaches for the right data structure immediately or writes unnecessarily complex code.

---

### Break down the requirements

#### Step 1: Initialize an empty frequency dict

A plain dict will map each character to its count. No imports needed.

#### Step 2: Iterate through each character

For each character, increment its count using `dict.get` with a default of 0, or check membership first.

#### Step 3: Return the frequency dict

Empty strings naturally produce an empty dict since the loop never executes.

---

### The solution

**Single-pass frequency accumulation**

```python
def char_count(s: str) -> dict:
    freq = {}
    for ch in s:
        if ch in freq:
            freq[ch] += 1
        else:
            freq[ch] = 1
    return freq
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the length of the string. Each character is processed in constant time.
> 
> **Space:** O(k) where k is the number of unique characters. At most 256 for ASCII input.

> **Interviewers Watch For**
>
> Whether you use `collections.Counter` vs a manual loop. Both are valid, but interviewers want to see you can write the loop manually to prove you understand the underlying mechanics.

> **Common Pitfall**
>
> Forgetting that spaces, digits, and special characters are all valid characters. The function should count everything, not just letters.

---

## Common follow-up questions

- How would you return results sorted by frequency descending? _(Tests sorting a dict by values, a common follow-up pattern.)_
- What if you needed case-insensitive counting? _(Tests string normalization with `.lower()` before counting.)_
- How would you find the k most frequent characters efficiently? _(Tests heap-based top-k selection or sorting tradeoffs.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_character_map)
- [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.