# The Letter Frequency Map

> Count every character in the string and report the results.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a string, return a dict mapping each distinct character (including spaces and punctuation) to its count.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests the most basic **frequency counting** pattern. It probes whether a candidate can build a frequency dict from scratch without relying on `collections.Counter`.

---

### Break down the requirements

#### Step 1: Initialize an empty dict

Map each character to its count.

#### Step 2: Iterate and count

For each character, increment its count in the dict.

---

### The solution

**Manual frequency dict construction**

```python
def char_frequency(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 string length.
> 
> **Space:** O(k) where k is the number of unique characters.

> **Interviewers Watch For**
>
> Whether you include spaces and punctuation. The problem says to include everything.

> **Common Pitfall**
>
> Filtering out non-letter characters when the problem asks for all characters including spaces and punctuation.

---

## Common follow-up questions

- How would you sort the output by frequency? _(Tests sorting dict items by value.)_
- What is the difference between this and collections.Counter? _(Tests that Counter does the same thing but also provides `.most_common()`.)_
- How would you handle a streaming input? _(Tests incremental counting without storing the full string.)_

## Related

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