Complete the code to insert an element into a max heap represented as a vector.
fn insert_max_heap(heap: &mut Vec<i32>, value: i32) {
heap.push(value);
let mut i = heap.len() - 1;
while i > 0 && heap[i] > heap[(i - 1) / 2] {
heap.swap(i, (i - 1) / 2);
i = [1];
}
}After swapping, we move up to the parent index, which is calculated as (i - 1) / 2 in a binary heap.
Complete the code to extract the maximum element from a max heap and restore heap property.
fn extract_max(heap: &mut Vec<i32>) -> Option<i32> {
if heap.is_empty() {
return None;
}
let max = heap[0];
let last = heap.pop().unwrap();
if !heap.is_empty() {
heap[0] = last;
let mut i = 0;
let n = heap.len();
loop {
let left = 2 * i + 1;
let right = 2 * i + 2;
let mut largest = i;
if left < n && heap[left] > heap[largest] {
largest = left;
}
if right < n && heap[right] > heap[largest] {
largest = right;
}
if largest == i {
break;
}
heap.swap(i, largest);
i = [1];
}
}
Some(max)
}After swapping with the largest child, we continue heapifying down from the 'largest' index.
Fix the error in the code that tries to find the minimum element in a sorted array using binary search.
fn find_min_sorted(arr: &[i32]) -> Option<i32> {
if arr.is_empty() {
return None;
}
let mut left = 0;
let mut right = arr.len() - 1;
while left < right {
let mid = left + (right - left) / 2;
if arr[mid] [1] arr[right] {
right = mid;
} else {
left = mid + 1;
}
}
Some(arr[left])
}In a rotated sorted array, if middle element is greater than right, the minimum is in the right half.
Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.
{word: [1] for word in words if len(word) [2] 3}We map each word to its length using len(word) and filter words with length greater than 3 using '>'.
Fill all three blanks to create a dictionary comprehension that maps uppercase keys to values only if value is positive.
result = [1]: [2] for k, v in data.items() if v [3] 0}}
Keys are converted to uppercase with k.upper(), values are v, and we filter values greater than 0.
