Character Frequency Counting in DSA Python - Time & Space Complexity
Counting how often each character appears in a string is a common task. We want to know how the time it takes grows as the string gets longer.
How does the number of steps change when the input string size increases?
Analyze the time complexity of the following code snippet.
text = "hello world"
frequency = {}
for char in text:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
print(frequency)
This code counts how many times each character appears in the given text string.
- Primary operation: Looping through each character in the string once.
- How many times: Exactly once for each character, so as many times as the string length.
As the string gets longer, the number of steps grows directly with the number of characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: Doubling the input size roughly doubles the work done.
Time Complexity: O(n)
This means the time to count characters grows in a straight line with the string length.
[X] Wrong: "Checking if a character is in the dictionary inside the loop makes it slower than linear."
[OK] Correct: Dictionary lookups are very fast (average constant time), so they do not add extra growth beyond the loop itself.
Understanding how simple loops and dictionary lookups work together helps you explain and write efficient code in interviews. It shows you can analyze and predict performance clearly.
"What if we used a nested loop to compare each character with every other character? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of frequency counting
Frequency counting means counting how many times each character appears in a string.Step 2: Compare options with the definition
Only How many times each character appears matches the purpose of character frequency counting.Final Answer:
How many times each character appears -> Option AQuick Check:
Frequency counting = count characters [OK]
- Confusing frequency with string length
- Thinking it finds character positions
- Mixing frequency with sorting
s?Solution
Step 1: Analyze each code snippet
freq = {}; for ch in s: freq[ch] = freq.get(ch, 0) + 1 uses a dictionary and increments count for each character correctly. freq = []; for ch in s: freq.append(ch) just collects characters in a list. freq = 0; for ch in s: freq += 1 counts total characters, not frequency per character. freq = {}; for ch in s: freq[ch] = 1 sets frequency to 1 always, ignoring repeats.Step 2: Confirm correct frequency counting logic
Only freq = {}; for ch in s: freq[ch] = freq.get(ch, 0) + 1 correctly counts how many times each character appears.Final Answer:
freq = {}; for ch in s: freq[ch] = freq.get(ch, 0) + 1 -> Option CQuick Check:
Use dict with get() to count [OK]
- Using list instead of dict for counting
- Overwriting counts instead of incrementing
- Counting total length instead of per character
text = 'hello'
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
print(freq)Solution
Step 1: Count characters in 'hello'
Characters: h(1), e(1), l(2), o(1)Step 2: Check code logic
Code correctly counts each character's frequency using dict and get().Final Answer:
{'h': 1, 'e': 1, 'l': 2, 'o': 1} -> Option BQuick Check:
Count 'l' twice, others once [OK]
- Counting 'l' only once
- Missing last character
- Incorrect dictionary format
text = 'apple'
freq = {}
for ch in text:
freq[ch] += 1
print(freq)Solution
Step 1: Identify how freq[ch] is updated
freq[ch] += 1 tries to add 1 to freq[ch] without initializing freq[ch] first.Step 2: Understand dictionary key initialization
Since freq is empty initially, freq[ch] does not exist and causes an error.Final Answer:
freq[ch] is used before initialization -> Option AQuick Check:
Initialize dict keys before incrementing [OK]
- Assuming dict keys auto-initialize
- Ignoring error messages
- Changing loop variable unnecessarily
s = 'banana', which code snippet correctly returns a dictionary with only characters that appear more than once?Solution
Step 1: Understand the goal
We want a dictionary with characters appearing more than once and their counts.Step 2: Analyze each option
freq = {ch: 1 for ch in s if s.count(ch) > 1} sets count to 1 always, ignoring actual counts. freq = {ch: s.count(ch) for ch in set(s) if s.count(ch) > 1} uses set(s) to avoid duplicates and filters counts > 1 correctly. freq = {ch for ch in s if s.count(ch) > 1} creates a set instead of dictionary with counts. freq = {ch: s.count(ch) for ch in s} includes all characters regardless of count.Final Answer:
freq = {ch: s.count(ch) for ch in set(s) if s.count(ch) > 1} -> Option DQuick Check:
Use set to avoid duplicates and filter counts [OK]
- Not using set to avoid duplicate keys
- Assigning wrong counts
- Including characters with single occurrence
Ready to prove it?
Pass the test and this pattern moves unknown
