Complete the code to initialize the variable that stores the count of subarrays.
let mut count = [1];We start counting subarrays from zero, so initializing count to 0 is correct.
Complete the code to update the cumulative sum with the current number.
sum [1] num;We add the current number to the cumulative sum to keep track of the total so far.
Fix the error in the code to check if the map contains the key for (sum - k).
if let Some(&freq) = map.get(&[1]) { count += freq; }
We look for the frequency of (sum - k) because it indicates a subarray summing to k.
Fill both blanks to update the map with the current sum frequency.
let entry = map.entry([1]).or_insert([2]); *entry += 1;
We insert the current sum with initial frequency 0 if not present, then increment it.
Fill all three blanks to complete the function that returns the count of subarrays summing to k.
fn subarray_sum(nums: Vec<i32>, k: i32) -> i32 {
use std::collections::HashMap;
let mut count = [1];
let mut sum = 0;
let mut map = HashMap::new();
map.insert(0, 1);
for num in nums {
sum [2] num;
if let Some(&freq) = map.get(&[3]) {
count += freq;
}
let entry = map.entry(sum).or_insert(0);
*entry += 1;
}
count
}The function initializes count to 0, adds each number to sum, checks for (sum - k) in the map, and updates count accordingly.
