The Letter Ledger
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L4
- Asked in
- Nintendo
Problem
Return how often each character of text appears as [char, count] pairs, sorted by character code from lowest to highest, so 'A' comes before 'a' and punctuation lands wherever its code falls. We count every character exactly as written except spaces, through a CharFrequency class whose get_counts() returns those sorted pairs and which char_frequency(text) builds and returns.
Every character has a count to answer for.
Example 1
Input:
text = "hello world"
Output:
[["d",1],["e",1],["h",1],["l",3],["o",2],["r",1],["w",1]]
Example 2
Input:
text = "Hello, World!"
Output:
[["!",1],[",",1],["H",1],["W",1],["d",1],["e",1],["l",3],["o",2],["r",1]]
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 pairs
Return [character, count] two-element lists sorted alphabetically by character.
Step 3: Provide the driver entrypoint
Expose a top-level char_frequency(text) driver that constructs the class and returns get_counts(), so the harness has a single callable entrypoint.
The solution
def char_frequency(text):
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:
result = []
for key in sorted(self.freq.keys()):
result.append([key, self.freq[key]])
return result
return CharFrequency(text).get_counts()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.)