Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the first occurrence index of target in the array.
DSA Rust
fn first_occurrence(arr: &[i32], target: i32) -> Option<usize> {
for i in 0..arr.len() {
if arr[i] == [1] {
return Some(i);
}
}
None
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the index variable instead of the target value in the comparison.
Comparing arr[i] to 0 instead of the target.
✗ Incorrect
We compare each element arr[i] with the target value to find the first occurrence.
2fill in blank
mediumComplete the code to find the last occurrence index of target in the array.
DSA Rust
fn last_occurrence(arr: &[i32], target: i32) -> Option<usize> {
let mut result = None;
for i in 0..arr.len() {
if arr[i] == [1] {
result = Some(i);
}
}
result
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing arr[i] to the index i instead of the target.
Assigning result to None inside the loop.
✗ Incorrect
We update result whenever we find an element equal to the target, so the last occurrence is stored.
3fill in blank
hardFix the error in the code to correctly find the first occurrence of target using a while loop.
DSA Rust
fn first_occurrence_while(arr: &[i32], target: i32) -> Option<usize> {
let mut i = 0;
while i < arr.len() {
if arr[i] == [1] {
return Some(i);
}
i += 1;
}
None
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing arr[i] to the index i instead of the target.
Using a wrong variable in the if condition.
✗ Incorrect
The comparison must be between the current element arr[i] and the target value.
4fill in blank
hardFill both blanks to create a function that returns a tuple with first and last occurrence indices of target.
DSA Rust
fn first_and_last(arr: &[i32], target: i32) -> (Option<usize>, Option<usize>) {
let mut first = None;
let mut last = None;
for i in 0..arr.len() {
if arr[i] == [1] {
if first.is_none() {
first = Some(i);
}
last = [2];
}
}
(first, last)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i instead of Some(i) for last.
Comparing arr[i] to i instead of target.
✗ Incorrect
We check if arr[i] equals target, set first if not set, and update last to Some(i) each time.
5fill in blank
hardFill all three blanks to create a function that returns a tuple with first and last occurrence indices using iterators and enumerate.
DSA Rust
fn first_and_last_iter(arr: &[i32], target: i32) -> (Option<usize>, Option<usize>) {
let mut first = None;
let mut last = None;
for (i, &val) in arr.iter().enumerate() {
if val == [1] {
if first == [2] {
first = Some(i);
}
last = [3];
}
}
(first, last)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Some(i) instead of None in the if condition.
Assigning last to Some(val) instead of Some(i).
✗ Incorrect
We compare val to target, check if first is None, and update last to Some(i).
