Character Frequency Counting in DSA Rust - Time & Space Complexity
We want to understand how long it takes to count how often each character appears in a string.
How does the time needed grow as the string gets longer?
Analyze the time complexity of the following code snippet.
use std::collections::HashMap;
fn char_frequency(s: &str) -> HashMap {
let mut freq = HashMap::new();
for ch in s.chars() {
*freq.entry(ch).or_insert(0) += 1;
}
freq
}
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 the number of characters.
| 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: "Counting characters takes longer because of the hash map operations inside the loop."
[OK] Correct: Each hash map insertion or update is on average constant time, so it does not add extra growth beyond the loop over characters.
Knowing how to analyze simple loops with hash maps helps you explain efficient counting and lookup tasks clearly in interviews.
"What if we used a sorted array instead of a hash map to store counts? How would the time complexity change?"
Practice
Solution
Step 1: Understand the meaning of frequency counting
Frequency counting means counting how often each item appears.Step 2: Apply to characters in a string
For characters, it means counting how many times each character shows up in the string.Final Answer:
Counting how many times each character appears in a string -> Option AQuick Check:
Frequency counting = Counting occurrences [OK]
- Confusing frequency counting with sorting
- Thinking frequency means replacing characters
- Mixing frequency with removing duplicates
Solution
Step 1: Identify the data structure for frequency counting
Frequency counting needs a map to store character keys and counts as values.Step 2: Check Rust syntax for creating an empty map
HashMap::new() creates an empty map; mut allows adding entries.Final Answer:
let mut freq = std::collections::HashMap::new(); -> Option AQuick Check:
Empty map initialization = HashMap::new() [OK]
- Using Vec or String instead of HashMap
- Not making the map mutable
- Initializing with a number instead of a map
use std::collections::HashMap;
fn main() {
let text = "hello";
let mut freq = HashMap::new();
for ch in text.chars() {
*freq.entry(ch).or_insert(0) += 1;
}
println!("{:?}", freq);
}Solution
Step 1: Count each character in "hello"
Characters: h(1), e(1), l(2), o(1).Step 2: Check code logic for counting
Code increments count for each character correctly using or_insert(0) and += 1.Final Answer:
{"h": 1, "e": 1, "l": 2, "o": 1} -> Option CQuick Check:
Count 'l' twice, others once [OK]
- Counting 'l' only once
- Confusing keys and values in map
- Assuming zero counts for characters
use std::collections::HashMap;
fn main() {
let text = "abcabc";
let mut freq = HashMap::new();
for ch in text.chars() {
freq.insert(ch, freq[&ch] + 1);
}
println!("{:?}", freq);
}Solution
Step 1: Understand freq[&ch] usage
freq[&ch] tries to get value for key ch but panics if key missing.Step 2: Identify missing key problem
On first occurrence, key ch is missing, so freq[&ch] causes runtime panic.Final Answer:
Using freq[&ch] causes panic if key not present -> Option DQuick Check:
Accessing missing key with [] panics [OK]
- Assuming freq[&ch] returns 0 if key missing
- Not making HashMap mutable
- Thinking text.chars() is wrong syntax
Solution
Step 1: Filter only alphabetic characters
Use filter with is_alphabetic() to keep letters only.Step 2: Count frequencies on filtered characters
Count frequencies on filtered chars to ignore digits/symbols.Final Answer:
Use chars().filter(|c| c.is_alphabetic()) and count frequencies -> Option BQuick Check:
Filter letters first, then count [OK]
- Counting digits and symbols by mistake
- Using bytes which may split characters wrongly
- Replacing digits but forgetting symbols
Ready to prove it?
Pass the test and this pattern moves unknown
