📖 Scenario: You are working with daily sales data for a small shop. You want to quickly find the total sales from the start of the week up to any given day.
🎯 Goal: Build a prefix sum array that stores cumulative sales totals for each day. This will help answer queries about total sales up to any day efficiently.
📋 What You'll Learn
Create a vector called daily_sales with exact values for 7 days
Create a vector called prefix_sums to store cumulative sums
Use a for loop with index i to build the prefix sums
Print the prefix_sums vector at the end
💡 Why This Matters
🌍 Real World
Prefix sums are used in finance, data analysis, and gaming to quickly calculate totals over ranges without repeated addition.
💼 Career
Understanding prefix sums helps in optimizing algorithms and solving problems efficiently in software engineering roles.
Progress0 / 4 steps
1
Create the daily sales data
Create a vector called daily_sales with these exact values: 10, 20, 15, 5, 30, 25, 10
DSA Rust
Hint
Use vec![...] to create a vector with the exact sales numbers.
2
Prepare the prefix sums vector
Create a mutable vector called prefix_sums with the same length as daily_sales, initialized with zeros
DSA Rust
Hint
Use vec![0; daily_sales.len()] to create a vector of zeros with the same length.
3
Calculate the prefix sums
Use a for loop with index i from 0 to daily_sales.len() to fill prefix_sums. For i == 0, set prefix_sums[0] to daily_sales[0]. For other i, set prefix_sums[i] to prefix_sums[i - 1] + daily_sales[i]
DSA Rust
Hint
Use for i in 0..daily_sales.len() and an if to handle the first element separately.
4
Print the prefix sums
Print the prefix_sums vector using println!("{:?}", prefix_sums)
DSA Rust
Hint
Use println!("{:?}", prefix_sums) to print the vector in debug format.
Practice
(1/5)
1. What does a prefix sum array represent for a given array arr?
easy
A. An array where each element is the difference between consecutive elements in arr
B. An array where each element is the product of all elements up to that index in arr
C. An array where each element is the sum of all elements up to that index in arr
D. An array where each element is the maximum value found up to that index in arr
Solution
Step 1: Understand prefix sum definition
A prefix sum array stores sums of elements from the start of the original array up to each index.
Step 2: Compare options with definition
Only An array where each element is the sum of all elements up to that index in arr matches this definition exactly, describing cumulative sums.
Final Answer:
An array where each element is the sum of all elements up to that index in arr -> Option C
Quick Check:
Prefix sum = cumulative sum [OK]
Hint: Prefix sum means cumulative sum from start to current index [OK]
Common Mistakes:
Confusing prefix sum with product or max operations
Thinking prefix sum stores differences between elements
Assuming prefix sum stores only the last element's value
2. Which of the following Rust code snippets correctly initializes a prefix sum array prefix from an integer vector arr?
easy
A. let mut prefix = vec![0; arr.len()]; prefix[0] = arr[0]; for i in 1..arr.len() { prefix[i] = prefix[i-1] + arr[i]; }
B. let mut prefix = vec![0; arr.len()]; for i in 0..arr.len() { prefix[i] = arr[i] + prefix[i+1]; }
C. let prefix = arr.iter().map(|x| *x).collect::();
D. let mut prefix = vec![0; arr.len()]; prefix[0] = 0; for i in 1..arr.len() { prefix[i] = prefix[i-1] * arr[i]; }
Solution
Step 1: Check initialization and first element assignment
let mut prefix = vec![0; arr.len()]; prefix[0] = arr[0]; for i in 1..arr.len() { prefix[i] = prefix[i-1] + arr[i]; } initializes prefix with zeros, sets prefix[0] = arr[0], which is correct.
Step 2: Verify loop logic for prefix sums
let mut prefix = vec![0; arr.len()]; prefix[0] = arr[0]; for i in 1..arr.len() { prefix[i] = prefix[i-1] + arr[i]; } loops from 1 to end, adding prefix[i-1] + arr[i], correctly building prefix sums.
Final Answer:
let mut prefix = vec![0; arr.len()]; prefix[0] = arr[0]; for i in 1..arr.len() { prefix[i] = prefix[i-1] + arr[i]; } -> Option A
Quick Check:
Correct prefix sum loop syntax [OK]
Hint: Start prefix[0] = arr[0], then add previous prefix + current arr [OK]
Common Mistakes:
Using prefix[i+1] inside loop causing out-of-bounds
Multiplying instead of adding elements
Not initializing prefix[0] before loop
3. Given the Rust code below, what is the printed output?
let arr = vec![2, 4, 6, 8];
let mut prefix = vec![0; arr.len()];
prefix[0] = arr[0];
for i in 1..arr.len() {
prefix[i] = prefix[i-1] + arr[i];
}
println!("{:?}", prefix);
The prefix array is [2, 6, 12, 20], matching [2, 6, 12, 20].
Final Answer:
[2, 6, 12, 20] -> Option D
Quick Check:
Sum accumulates correctly [OK]
Hint: Add each element to previous prefix sum [OK]
Common Mistakes:
Printing original array instead of prefix
Starting prefix sums from zero incorrectly
Miscomputing sums by skipping elements
4. Identify the error in the following Rust code that attempts to create a prefix sum array and fix it:
let arr = vec![1, 3, 5];
let mut prefix = vec![0; arr.len()];
for i in 0..arr.len() {
prefix[i] = prefix[i-1] + arr[i];
}
println!("{:?}", prefix);
medium
A. The loop starts at 0 but uses prefix[i-1], causing out-of-bounds; start loop at 1 and set prefix[0] = arr[0]
B. The vector prefix is not mutable; add mut keyword
C. The arr vector is empty; initialize with values
D. The println! macro is missing a semicolon
Solution
Step 1: Identify cause of out-of-bounds error
At i=0, prefix[i-1] is prefix[-1], which is invalid in Rust and causes panic.
Step 2: Fix loop and initialization
Set prefix[0] = arr[0] before loop, then loop from i=1 to arr.len()-1 to safely access prefix[i-1].
Final Answer:
The loop starts at 0 but uses prefix[i-1], causing out-of-bounds; start loop at 1 and set prefix[0] = arr[0] -> Option A
Quick Check:
Indexing prefix[i-1] at i=0 causes error [OK]
Hint: Avoid negative indexing; initialize first element before loop [OK]
Common Mistakes:
Starting loop at 0 and accessing prefix[i-1]
Not initializing prefix[0] before loop
Ignoring Rust's strict bounds checking
5. You have an array arr = [3, 1, 4, 1, 5, 9, 2]. Using a prefix sum array, how would you efficiently find the sum of elements between indices 2 and 5 (inclusive)?
hard
A. Calculate prefix sums, then sum = prefix[5] + prefix[2]
B. Calculate prefix sums, then sum = prefix[5] - prefix[1]
C. Calculate prefix sums, then sum = prefix[5] - prefix[2]
D. Calculate prefix sums, then sum = prefix[6] - prefix[2]
Solution
Step 1: Understand prefix sum usage for range sums
Sum from index l to r = prefix[r] - prefix[l-1], assuming prefix sums start at index 0.
Step 2: Apply to given indices 2 to 5
Sum = prefix[5] - prefix[1], since prefix[1] is sum up to index 1.
Final Answer:
Calculate prefix sums, then sum = prefix[5] - prefix[1] -> Option B
Quick Check:
Range sum = prefix[r] - prefix[l-1] [OK]
Hint: Range sum = prefix[end] - prefix[start-1] [OK]
Common Mistakes:
Subtracting prefix[start] instead of prefix[start-1]
Adding prefix values instead of subtracting
Using wrong indices for prefix subtraction
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.