The Letter Frequency Map
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
- L3
- Asked in
- Nintendo
Problem
Given a string, return a dict mapping each distinct character (including spaces and punctuation) to its count.
Count every character in the string and report the results.
Example 1
Input:
s = "hello"
Output:
{"h":1,"e":1,"l":2,"o":1}Example 2
Input:
s = "aab"
Output:
{"a":2,"b":1}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
def char_frequency(s: str) -> dict:
freq = {}
for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
return freqCommon 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.)