Character Frequency Counting in DSA C++ - Time & Space Complexity
Counting how often each character appears in a string is a common task. We want to know how the time needed grows as the string gets longer.
How does the work change when the input string size increases?
Analyze the time complexity of the following code snippet.
#include <iostream>
#include <unordered_map>
#include <string>
void countFrequency(const std::string &s) {
std::unordered_map<char, int> freq;
for (char c : s) {
freq[c]++;
}
}
This code counts how many times each character appears in the input string.
Identify the loops, recursion, array traversals that repeat.
- 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 its length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows in a straight line with input size; doubling input doubles work.
Time Complexity: O(n)
This means the time to count characters grows directly with the string length.
[X] Wrong: "Since we use a map inside the loop, the time is more than linear, maybe quadratic."
[OK] Correct: Each map insertion or update is on average constant time, so it does not multiply the loop time.
Understanding how simple loops and data structures affect time helps you explain your code clearly and choose the right approach in interviews.
"What if we used a sorted map instead of an unordered map? How would the time complexity change?"
Practice
Solution
Step 1: Understand character frequency counting
It means counting how many times each character shows up in the string.Step 2: Compare with options
Only How many times each character appears in the string matches this meaning exactly.Final Answer:
How many times each character appears in the string -> Option DQuick Check:
Frequency counting = count characters [OK]
- Confusing frequency with string length
- Thinking frequency means position
- Mixing frequency with substring extraction
Solution
Step 1: Identify correct map declaration
We need a map with key as char and value as int to count frequencies.Step 2: Check each option
std::map freq; uses std::map, which is correct. Others have wrong types or missing template parameters.Final Answer:
std::map freq; -> Option AQuick Check:
Map key=char, value=int for frequency [OK]
- Using vector instead of map
- Swapping key and value types
- Missing template parameters in map
std::string s = "hello";
std::map freq;
for (char c : s) {
freq[c]++;
}
for (auto &p : freq) {
std::cout << p.first << ":" << p.second << " ";
}Solution
Step 1: Count characters in "hello"
h=1, e=1, l=2, o=1Step 2: Understand map iteration order
std::map orders keys ascending by character: e, h, l, oFinal Answer:
e:1 h:1 l:2 o:1 -> Option BQuick Check:
Map sorts keys alphabetically [OK]
- Assuming insertion order output
- Mixing character counts
- Ignoring map key sorting
std::string s = "abcabc";
std::map freq;
for (int i = 0; i <= s.size(); i++) {
freq[s[i]]++;
}Solution
Step 1: Check loop boundary
Loop runs from i=0 to i <= s.size(), which accesses s[s.size()] out of bounds.Step 2: Correct loop condition
It should be i < s.size() to avoid out-of-range access.Final Answer:
Loop condition should be i < s.size(), not <= s.size() -> Option CQuick Check:
Index must be less than string length [OK]
- Off-by-one error in loop
- Wrong map type confusion
- Incorrect frequency increment logic
Solution
Step 1: Count character frequencies using a map
Use std::map to count how many times each character appears.Step 2: Iterate map to find character with max frequency
Loop through map entries to track character with highest count.Final Answer:
Count frequencies in a map, then iterate to find max frequency character -> Option AQuick Check:
Map + iteration finds max frequency char [OK]
- Sorting string doesn't give max frequency
- Using vector or queue wrongly
- Not iterating to find max frequency
Ready to prove it?
Pass the test and this pattern moves unknown
