Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the pattern exists in the text using the contains method.
DSA Rust
let text = "hello world"; let pattern = "world"; let found = text.[1](pattern); println!("Pattern found: {}", found);
Attempts:
3 left
💡 Hint
Common Mistakes
Using starts_with or ends_with which only check beginning or end of the string.
Using find which returns an Option, not a boolean.
✗ Incorrect
The contains method checks if the pattern is present anywhere in the text and returns true or false.
2fill in blank
mediumComplete the code to find the starting index of the pattern in the text using the find method.
DSA Rust
let text = "rust programming"; let pattern = "program"; let index = text.[1](pattern); println!("Pattern starts at: {:?}", index);
Attempts:
3 left
💡 Hint
Common Mistakes
Using contains which returns a boolean, not an index.
Using position which is for iterators, not strings.
✗ Incorrect
The find method returns an Option with the starting index of the pattern if found.
3fill in blank
hardFix the error in the code to correctly get the substring from the found index.
DSA Rust
let text = "data structures"; let pattern = "struct"; if let Some(start) = text.[1](pattern) { let substring = &text[start..start + pattern.len()]; println!("Found substring: {}", substring); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using contains which returns a boolean, causing a type mismatch.
Using position which is not a method on strings.
✗ Incorrect
The find method returns the starting index of the pattern, which can be used to slice the string.
4fill in blank
hardFill both blanks to create a loop that finds all occurrences of the pattern in the text.
DSA Rust
let text = "ababababa"; let pattern = "aba"; let mut start = 0; while let Some(pos) = text[start..].[1](pattern) { let index = start + pos; println!("Found at index: {}", index); start = index + [2]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using contains instead of find which does not return position.
Incrementing start by 1 causing infinite loops or repeated matches.
✗ Incorrect
Use find to get the next occurrence index, then move start by the pattern length to avoid overlapping matches.
5fill in blank
hardFill all three blanks to build a HashMap counting occurrences of each pattern in a list of texts.
DSA Rust
use std::collections::HashMap; let texts = vec!["apple pie", "apple tart", "banana pie"]; let pattern = "pie"; let mut counts = HashMap::new(); for text in texts { if text.[1](pattern) { *counts.entry(text.[2]()).or_insert(0) += [3]; } } println!("Counts: {:?}", counts);
Attempts:
3 left
💡 Hint
Common Mistakes
Using find instead of contains for boolean check.
Not converting &str to String causing type errors.
Incrementing count by wrong value.
✗ Incorrect
Use contains to check presence, to_string to convert &str to String for HashMap key, and increment count by 1.
