# The Letter Tally

> Each character in the string has a count to answer for.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Implement CharCounter(text) with method get_counts() returning a list of [char, count] pairs sorted alphabetically by character. Ignore spaces and punctuation. Test harness constructs the class from the input string and calls get_counts.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **class-based frequency counting** with filtering, combining OOP with the dict accumulation pattern. It probes constructor initialization, character filtering, and sorted tuple output.

---

### Break down the requirements

#### Step 1: Count frequencies in __init__, ignoring spaces and punctuation

Only count alphanumeric characters.

#### Step 2: get_counts returns sorted (char, count) tuples

Sort alphabetically by character.

---

### The solution

**Class with filtered frequency counting**

```python
class CharCounter:
    def __init__(self, text: str):
        self.freq = {}
        for ch in text:
            if not ch.isalnum():
                continue
            if ch in self.freq:
                self.freq[ch] += 1
            else:
                self.freq[ch] = 1
    def get_counts(self) -> list:
        sorted_keys = sorted(self.freq.keys())
        result = []
        for key in sorted_keys:
            result.append((key, self.freq[key]))
        return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) for construction, O(k log k) for `get_counts`.
> 
> **Space:** O(k) for the frequency dict.

> **Interviewers Watch For**
>
> Whether you use `isalnum()` to filter spaces and punctuation. Using `isalpha()` would also exclude digits.

> **Common Pitfall**
>
> Including spaces and punctuation in the count. Read the requirements carefully to determine which characters to skip.

---

## Common follow-up questions

- What if case should be ignored? _(Tests normalizing with `.lower()` before counting.)_
- How would you return the top-k most frequent characters? _(Tests sorting by value and slicing.)_
- What if the text is very large? _(Tests streaming construction, counting character by character without storing the full text.)_

## Related

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