Challenge - 5 Problems
Character Frequency Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of character frequency count in Rust
What is the output of the following Rust code that counts character frequencies in a string?
DSA Rust
use std::collections::HashMap;
fn main() {
let text = "hello world";
let mut freq = HashMap::new();
for ch in text.chars() {
*freq.entry(ch).or_insert(0) += 1;
}
let mut result: Vec<(char, i32)> = freq.into_iter().collect();
result.sort_by_key(|&(c, _)| c);
for (c, count) in result {
print!("{}:{} ", c, count);
}
}
Attempts:
2 left
💡 Hint
Look carefully at how the characters are sorted before printing.
✗ Incorrect
The code counts each character's frequency, including spaces. Then it sorts by character (space comes first), so output starts with space and its count, followed by characters in alphabetical order.
🧠 Conceptual
intermediateUnderstanding character frequency map size
Given the string "abracadabra", how many unique characters will the frequency map contain after counting?
Attempts:
2 left
💡 Hint
Count distinct letters in the word.
✗ Incorrect
The unique characters are a, b, r, c, d. Counting carefully, 'a', 'b', 'r', 'c', 'd' are 5 distinct letters, but 'a' appears multiple times. The unique count is 5.
🔧 Debug
advancedIdentify the error in character frequency counting code
What error will this Rust code produce when counting character frequencies?
let text = "test";
let mut freq = std::collections::HashMap::new();
for ch in text.chars() {
freq.insert(ch, freq[&ch] + 1);
}
println!("{:?}", freq);
Attempts:
2 left
💡 Hint
Check how freq[&ch] is accessed before insertion.
✗ Incorrect
Accessing freq[&ch] without ensuring the key exists causes a panic (runtime error) because the key might not be present on first insertion.
❓ Predict Output
advancedOutput of frequency counting with filtering
What is the output of this Rust code that counts only alphabetic characters in "a1b2c3a"?
DSA Rust
use std::collections::HashMap;
fn main() {
let text = "a1b2c3a";
let mut freq = HashMap::new();
for ch in text.chars() {
if ch.is_alphabetic() {
*freq.entry(ch).or_insert(0) += 1;
}
}
let mut result: Vec<(char, i32)> = freq.into_iter().collect();
result.sort_by_key(|&(c, _)| c);
for (c, count) in result {
print!("{}:{} ", c, count);
}
}
Attempts:
2 left
💡 Hint
Only alphabetic characters are counted.
✗ Incorrect
Digits are skipped by the if condition, so only 'a', 'b', 'c' are counted. 'a' appears twice, 'b' and 'c' once each.
🧠 Conceptual
expertMemory complexity of character frequency counting
What is the memory complexity of counting character frequencies in a string of length n containing only ASCII characters?
Attempts:
2 left
💡 Hint
Think about the maximum number of unique characters possible.
✗ Incorrect
Since ASCII has a fixed set of 128 characters, the frequency map size is capped at 128 keys, so memory is constant regardless of string length.
