If slice length is 1, return that element. Otherwise, split slice and sum recursively.
Step 2: Calculate sum for [2,4,6,8]
Split into [2,4] and [6,8]. sum_slice([2,4]) = 2+4=6, sum_slice([6,8])=6+8=14. Total = 6+14=20.
Final Answer:
20 -> Option B
Quick Check:
2+4+6+8 = 20 [OK]
Hint: Sum = add halves recursively [OK]
Common Mistakes:
Confusing slice ranges causing wrong sums
Forgetting base case returns single element
Assuming runtime error due to slicing
4. This Rust function aims to find the maximum element using divide and conquer:
fn max_element(arr: &[i32]) -> i32 {
if arr.len() == 1 {
arr[0]
} else {
let mid = arr.len() / 2;
let left_max = max_element(&arr[..mid]);
let right_max = max_element(&arr[mid..]);
if left_max > right_max {
left_max
} else {
right_max
}
}
}
But when called with an empty slice, it panics. How to fix it?
medium
A. Add a check for empty slice and return a default or Option
B. Remove the base case and always split the slice
C. Change the function to return i32::MIN unconditionally
D. Use a loop instead of recursion
Solution
Step 1: Identify cause of panic
With an empty slice (arr.len() == 0), the base case (len == 1) is skipped, mid = 0, and it recurses on two empty slices, causing infinite recursion and stack overflow panic.
Step 2: Fix by checking empty slice
Add a condition to handle empty slice, e.g., return Option<i32> or a default value.
Final Answer:
Add a check for empty slice and return a default or Option -> Option A
Quick Check:
Empty slice needs special handling [OK]
Hint: Check for empty input before accessing elements [OK]
Common Mistakes:
Ignoring empty slice case
Removing base case causing infinite recursion
Returning fixed min value without condition
5. You want to use divide and conquer to count how many numbers in a large array are greater than 10. Which approach best uses divide and conquer benefits?
hard
A. Sort the array first, then count numbers > 10 using binary search
B. Iterate the entire array once and count numbers > 10
C. Split the array into halves, count in each half recursively, then sum counts
D. Use a loop to check each element without splitting
Solution
Step 1: Understand divide and conquer for counting
Divide array into smaller parts, count in each, then combine results.
Step 2: Compare options
Split the array into halves, count in each half recursively, then sum counts uses divide and conquer by splitting and summing counts. Others do not split or use different methods.
Final Answer:
Split the array into halves, count in each half recursively, then sum counts -> Option C
Quick Check:
Divide and conquer = split, solve, combine [OK]
Hint: Divide problem, count parts, then add results [OK]
Common Mistakes:
Choosing simple iteration ignoring divide and conquer
Sorting unnecessarily before counting
Not combining results after splitting
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.