Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if a solution is valid in backtracking.
DSA Rust
fn is_valid(solution: &Vec<i32>, candidate: i32) -> bool {
for &item in solution.iter() {
if item == [1] {
return false;
}
}
true
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing item with solution length instead of candidate.
Returning true inside the loop prematurely.
✗ Incorrect
We check if the candidate is already in the solution to avoid duplicates.
2fill in blank
mediumComplete the code to backtrack by removing the last candidate.
DSA Rust
fn backtrack(solution: &mut Vec<i32>, candidates: &Vec<i32>) {
if solution.len() == candidates.len() {
println!("Solution: {:?}", solution);
return;
}
for &candidate in candidates.iter() {
if is_valid(solution, candidate) {
solution.push(candidate);
backtrack(solution, candidates);
solution.[1]();
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using clear() which removes all elements.
Using remove() without index which causes error.
✗ Incorrect
We use pop() to remove the last added candidate to try other options.
3fill in blank
hardFix the error in the greedy approach that fails to find the correct solution.
DSA Rust
fn greedy_select(weights: &Vec<i32>, values: &Vec<i32>, capacity: i32) -> i32 {
let mut total_value = 0;
let mut remaining = capacity;
for i in 0..weights.len() {
if weights[i] <= [1] {
total_value += values[i];
remaining -= weights[i];
}
}
total_value
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking weights[i] <= capacity always, ignoring remaining capacity.
Adding values without checking weight.
✗ Incorrect
We must check if the current item's weight fits in the remaining capacity, not the original capacity.
4fill in blank
hardFill both blanks to implement backtracking for subset sum problem.
DSA Rust
fn subset_sum(nums: &Vec<i32>, index: usize, target: i32, current_sum: i32) -> bool {
if current_sum == target {
return true;
}
if index == nums.len() || current_sum > target {
return false;
}
if subset_sum(nums, index + 1, [1], current_sum + nums[index]) {
return true;
}
if subset_sum(nums, index + 1, [2], current_sum) {
return true;
}
false
}Attempts:
3 left
💡 Hint
Common Mistakes
Passing wrong arguments order.
Using target or current_sum as index.
✗ Incorrect
We pass index + 1 and keep target and current_sum updated correctly in recursive calls.
5fill in blank
hardFill all three blanks to implement backtracking for generating permutations.
DSA Rust
fn permute(nums: &mut Vec<i32>, start: usize, result: &mut Vec<Vec<i32>>) {
if start == nums.len() {
result.push(nums.clone());
return;
}
for i in start..nums.len() {
nums.[1](start, i);
permute(nums, [2], result);
nums.[3](start, i);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of swap.
Not incrementing start in recursive call.
✗ Incorrect
We swap elements to generate permutations, recurse with start + 1, then swap back to restore order.
