# The Letter Ledger

> Every character has a count to answer for.

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

Domain: Python · Difficulty: easy · Seniority: L4

## Problem

Implement CharFrequency(s) with method get_counts() returning a list of [char, count] pairs for distinct characters in s, sorted alphabetically. Ignore spaces. Test harness constructs the class and calls .get_counts().

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **class design with frequency counting**, combining OOP basics with the dict accumulation pattern. It probes constructor logic, method implementation, and sorted output.

---

### Break down the requirements

#### Step 1: Count character frequencies in __init__

Build a frequency dict, ignoring spaces.

#### Step 2: get_counts returns sorted tuples

Return `(character, count)` pairs sorted alphabetically by character.

---

### The solution

**Class-based character frequency tracker**

```python
class CharFrequency:
    def __init__(self, text: str):
        self.freq = {}
        for ch in text:
            if ch == ' ':
                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` where k is the number of unique characters.
> 
> **Space:** O(k) for the frequency dict.

> **Interviewers Watch For**
>
> Whether you store the frequency dict as an instance attribute so `get_counts` can access it without recomputing.

> **Common Pitfall**
>
> Including spaces in the count. The problem says to ignore spaces.

---

## Common follow-up questions

- What if get_counts should be sorted by frequency instead? _(Tests sorting by value with a key function.)_
- How would you make this class immutable? _(Tests computing counts once in __init__ and storing the sorted result.)_
- What if you needed to add more text after construction? _(Tests adding an `add_text` method that updates the frequency dict.)_

## Related

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