Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to recursively sum all elements in the array.
DSA Rust
fn sum_array(arr: &[i32], index: usize) -> i32 {
if index == arr.len() {
return 0;
}
arr[index] + [1](arr, index + 1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong function name causes a compile error.
Forgetting to increment the index leads to infinite recursion.
✗ Incorrect
The function calls itself recursively with the next index to sum all elements.
2fill in blank
mediumComplete the code to check if a string is a palindrome using recursion.
DSA Rust
fn is_palindrome(s: &str) -> bool {
if s.len() <= 1 {
return true;
}
let bytes = s.as_bytes();
if bytes[0] != bytes[s.len() - 1] {
return false;
}
is_palindrome(&s[1..[1]])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using s.len() includes the last character again causing infinite recursion.
Using s.len() - 2 removes too many characters.
✗ Incorrect
We remove the first and last characters each time, so the slice ends at length minus one.
3fill in blank
hardFix the error in the recursive function that counts occurrences of a target in an array.
DSA Rust
fn count_occurrences(arr: &[i32], target: i32, index: usize) -> i32 {
if index == arr.len() {
return 0;
}
let count = if arr[index] == target { 1 } else { 0 };
count + [1](arr, target, index + 1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a different function name causes a compile error.
Forgetting to increment index causes infinite recursion.
✗ Incorrect
The function must call itself by its exact name to recurse correctly.
4fill in blank
hardFill both blanks to recursively reverse a string slice.
DSA Rust
fn reverse_string(s: &str) -> String {
if s.is_empty() {
return String::new();
}
let last_char = &s[s.len() - 1..s.len()];
let rest = &s[0..[1]];
format!("{}{}", last_char, [2](rest))
}Attempts:
3 left
💡 Hint
Common Mistakes
Using s.len() includes the last character again causing incorrect slicing.
Using wrong function name causes compile error.
✗ Incorrect
We take the substring excluding the last character and recursively reverse it using the function name.
5fill in blank
hardFill the blanks to build a dictionary of word lengths for words longer than 3 characters.
DSA Rust
fn word_lengths(words: &[&str]) -> std::collections::HashMap<String, usize> {
let mut map = std::collections::HashMap::new();
for &word in words {
if word.len() > 3 {
map.insert([1].to_string(), [2]);
}
}
map
}
// Usage example:
// let words = ["apple", "bat", "carrot"];
// let result = word_lengths(&words);Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable for key or value.
Not converting the word to a string for the key.
✗ Incorrect
The key is the word as a string, and the value is the length of the word.
