Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new empty hash map.
DSA Rust
let mut counts = std::collections::HashMap::[1]();Attempts:
3 left
💡 Hint
Common Mistakes
Using insert instead of new to create the map.
Trying to get or remove before the map exists.
✗ Incorrect
We use HashMap::new() to create an empty hash map to store character counts.
2fill in blank
mediumComplete the code to increase the count of a character in the hash map.
DSA Rust
let count = counts.entry(ch).or_insert(0); *count [1] 1;
Attempts:
3 left
💡 Hint
Common Mistakes
Using -= which decreases the count.
Using * or / which are not for addition.
✗ Incorrect
We add 1 to the current count to track how many times the character appears.
3fill in blank
hardFix the error in the code to find the first non-repeating character.
DSA Rust
for ch in s.chars() { if counts.get(&ch) == Some(&[1]) { return Some(ch); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 0 which means character not present.
Checking for 2 or None which are incorrect.
✗ Incorrect
We check if the count is 1 to find the first character that appears only once.
4fill in blank
hardFill both blanks to complete the function that returns the first non-repeating character or None.
DSA Rust
fn first_non_repeating(s: &str) -> Option<char> {
let mut counts = std::collections::HashMap::[1]();
for ch in s.chars() {
let count = counts.entry(ch).or_insert(0);
*count [2] 1;
}
for ch in s.chars() {
if counts.get(&ch) == Some(&1) {
return Some(ch);
}
}
None
}Attempts:
3 left
💡 Hint
Common Mistakes
Using insert instead of new to create the map.
Using -= instead of += to update counts.
✗ Incorrect
We create a new hash map and add 1 to counts for each character.
5fill in blank
hardFill all three blanks to complete the main function that tests the first_non_repeating function.
DSA Rust
fn main() {
let s = "[1]";
match first_non_repeating(s) {
Some(ch) => println!("First non-repeating character: {}", [2]),
None => println!("No non-repeating character found."),
}
// Output should be: [3]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a string with no non-repeating characters.
Printing the wrong variable or output.
✗ Incorrect
We test with string "hello", print the found character ch, which should be 'h'.
