Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get the length of the pattern string.
DSA Rust
let pattern_len = pattern.[1]();Attempts:
3 left
💡 Hint
Common Mistakes
Using length() which does not exist for &str
Using size() or count() which are invalid methods here
✗ Incorrect
The correct method to get the length of a string slice in Rust is len().
2fill in blank
mediumComplete the code to get the length of the text string.
DSA Rust
let text_len = text.[1]();Attempts:
3 left
💡 Hint
Common Mistakes
Using length() which is not a method on &str
Using size() or count() which are invalid here
✗ Incorrect
The .len() method returns the length of the string slice in Rust.
3fill in blank
hardFix the error in the loop to iterate over possible start indices for matching.
DSA Rust
for i in 0..=text_len [1] pattern_len {
Attempts:
3 left
💡 Hint
Common Mistakes
Using + causes index out of bounds
Using * or / are invalid for index range
✗ Incorrect
We iterate from 0 up to text_len - pattern_len inclusive to avoid overflow.
4fill in blank
hardFill the blank to compare characters at current indices in text and pattern.
DSA Rust
if text[i[1]j] == pattern[j] {
Attempts:
3 left
💡 Hint
Common Mistakes
Using - causes negative indices
Using * or / are invalid for indexing
✗ Incorrect
We add j to i to get the correct character index in text, and use j as is for pattern.
5fill in blank
hardFill all three blanks to complete the naive string matching function.
DSA Rust
fn naive_search(text: &str, pattern: &str) -> Vec<usize> {
let mut result = Vec::new();
let text_len = text.[1]();
let pattern_len = pattern.[2]();
for i in 0..=text_len[3]pattern_len {
let mut j = 0;
while j < pattern_len && text[i + j] == pattern[j] {
j += 1;
}
if j == pattern_len {
result.push(i);
}
}
result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using length instead of len()
Using + instead of - in loop range
Not using .len() for lengths
✗ Incorrect
Use .len() to get lengths and subtract pattern_len from text_len for the loop range.
