Given the array [1, 3, 4, 5, 7] and target sum 8, what is the output of the two functions below?
Function brute_force_sum checks all pairs for sum. Function two_pointer_sum uses two pointers on sorted array.
fn brute_force_sum(arr: &[i32], target: i32) -> bool { for i in 0..arr.len() { for j in i+1..arr.len() { if arr[i] + arr[j] == target { return true; } } } false } fn two_pointer_sum(arr: &[i32], target: i32) -> bool { let mut left = 0; let mut right = arr.len() - 1; while left < right { let sum = arr[left] + arr[right]; if sum == target { return true; } else if sum < target { left += 1; } else { right -= 1; } } false } fn main() { let arr = [1, 3, 4, 5, 7]; let target = 8; println!("Brute Force: {}", brute_force_sum(&arr, target)); println!("Two Pointer: {}", two_pointer_sum(&arr, target)); }
Both methods check if any two numbers sum to the target. The array is sorted for two pointer.
Both functions find pairs that sum to 8: (1,7) and (3,5). So both return true.
Which statement best explains why the two pointer technique is faster than brute force for sorted arrays?
Think about how many pairs each method checks.
Two pointer moves from both ends inward, checking pairs in linear time O(n), while brute force checks all pairs O(n²).
What error will this Rust code cause when run?
fn two_pointer_sum(arr: &[i32], target: i32) -> bool {
let mut left = 0;
let mut right = arr.len();
while left < right {
let sum = arr[left] + arr[right];
if sum == target {
return true;
} else if sum < target {
left += 1;
} else {
right -= 1;
}
}
false
}Check how right is initialized and used as index.
Array indices go from 0 to len-1. Using arr.len() as index causes out of bounds panic.
Given a sorted array [1, 2, 2, 3, 4, 5] and target 5, which output shows all unique pairs found by a two pointer approach?
Two pointer skips duplicates to avoid repeated pairs.
Pairs (1,4) and (2,3) sum to 5. Duplicate (2,3) is not repeated.
Which condition makes the two pointer technique unsuitable compared to brute force?
Think about the requirement of two pointer technique.
Two pointer requires sorted array. If sorting is not allowed or possible, brute force is needed.
