Count how many times each character appears in a Python string with a dict, then with collections.Counter. O(n) time, practised with hidden tests.
The problem
Return a dictionary mapping each character of s to the number of times it appears.
Examples
Example 1
Input
char_frequency('programming')Expected output
{'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}Example 2
Input
char_frequency('aaa')Expected output
{'a': 3}
+ 2 hidden tests on Submit — spaces count too.
Edge cases to ask about
- Empty string
- Spaces and punctuation
- Upper vs lower case
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| s.count() per character | O(n·k) | O(k) | One full scan per distinct character. |
| bestOne counting pass | O(n) | O(k) | dict.get or collections.Counter. |
Walkthrough of the optimal approach (try it yourself first)
One pass, one dict: freq[ch] = freq.get(ch, 0) + 1. collections.defaultdict(int) and Counter are the idiomatic alternatives — know all three.
Complexity: O(n) time, O(k) space. One pass over the string; one dict entry per distinct character.
Reveal the reference solution
def char_frequency(s): freq = {} for ch in s: freq[ch] = freq.get(ch, 0) + 1 return freq
The brute force, for comparison
def char_frequency(s): return {ch: s.count(ch) for ch in s}
Follow-ups interviewers ask
- Return the most common character.
- Ignore case and non-letters.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Count Character Frequency in a String in Python?
The optimal solution runs in O(n) time and O(k) auxiliary space. One pass over the string; one dict entry per distinct character.
What is the brute-force approach, and how do you optimise it?
s.count() per character: O(n·k) time, O(k) space. One full scan per distinct character. One counting pass: O(n) time, O(k) space. dict.get or collections.Counter.
What follow-up questions do interviewers ask about Count Character Frequency in a String?
Return the most common character. Ignore case and non-letters.
