What if you could answer any sum question instantly without adding numbers again and again?
Why Prefix Sum Array in DSA Typescript?
Imagine you have a long list of daily expenses and you want to quickly find out how much you spent between any two days. Doing this by adding each day's expense every time you ask is like counting coins one by one every time you want to know your total.
Manually adding numbers for every query is slow and tiring. If you have many queries, you waste a lot of time repeating the same additions. It's easy to make mistakes, especially with long lists, and it feels like doing the same work again and again.
A prefix sum array keeps a running total of expenses up to each day. This way, to find the total between two days, you just subtract two numbers. It's like having a ready-made summary that saves you from counting coins repeatedly.
function sumRange(expenses: number[], start: number, end: number): number {
let total = 0;
for (let i = start; i <= end; i++) {
total += expenses[i];
}
return total;
}function createPrefixSum(expenses: number[]): number[] {
const prefixSum = [0];
for (let i = 0; i < expenses.length; i++) {
prefixSum.push(prefixSum[i] + expenses[i]);
}
return prefixSum;
}
function sumRange(prefixSum: number[], start: number, end: number): number {
return prefixSum[end + 1] - prefixSum[start];
}It makes answering sum queries super fast and easy, even for huge lists.
Bank apps use prefix sums to quickly show your spending between any two dates without recalculating every time you check.
Manually summing ranges is slow and error-prone.
Prefix sum arrays store running totals to speed up queries.
They make repeated sum queries efficient and simple.
Practice
prefix sum array in algorithms?Solution
Step 1: Understand what prefix sum array stores
A prefix sum array stores cumulative sums of elements from the start up to each index.Step 2: Identify the use of prefix sums
Using prefix sums, we can find the sum of any subarray quickly by subtracting two prefix sums.Final Answer:
To quickly find the sum of elements between any two indices -> Option AQuick Check:
Prefix sum array = fast range sum queries [OK]
- Confusing prefix sum with sorting
- Thinking prefix sum reverses array
- Assuming prefix sum finds max element
prefix for an input array arr?Solution
Step 1: Check initialization and loop indexing
const prefix = [0]; for(let i=0; iStep 2: Identify errors in other options
const prefix = []; for(let i=0; iFinal Answer:
const prefix = [0]; for(let i=0; i -> Option BQuick Check:
Prefix sum array starts with 0 and accumulates sums [OK]
- Accessing array out of bounds
- Not initializing prefix[0] to 0
- Using negative indices
const arr = [2, 4, 6, 8];
const prefix = [0];
for(let i = 0; i < arr.length; i++) {
prefix[i + 1] = prefix[i] + arr[i];
}
console.log(prefix);Solution
Step 1: Calculate prefix sums step-by-step
prefix[0] = 0 prefix[1] = 0 + 2 = 2 prefix[2] = 2 + 4 = 6 prefix[3] = 6 + 6 = 12 prefix[4] = 12 + 8 = 20Step 2: Confirm final prefix array
The prefix array is [0, 2, 6, 12, 20].Final Answer:
[0, 2, 6, 12, 20] -> Option CQuick Check:
Sum accumulates correctly in prefix array [OK]
- Forgetting initial 0 in prefix
- Adding wrong elements in loop
- Off-by-one errors in indexing
const arr = [1, 3, 5];
const prefix = [];
for(let i = 0; i < arr.length; i++) {
prefix[i + 1] = prefix[i] + arr[i];
}
console.log(prefix);Solution
Step 1: Check prefix array initialization
The prefix array is empty initially, so prefix[0] is undefined.Step 2: Identify impact on prefix sum calculation
prefix[i] is undefined for i=0, so prefix[1] = undefined + arr[0] results in NaN.Final Answer:
prefix array is not initialized with 0 at index 0 -> Option AQuick Check:
Initialize prefix[0] = 0 to avoid NaN [OK]
- Not initializing prefix[0]
- Assuming empty array has prefix[0]
- Ignoring NaN results
arr = [3, 1, 4, 1, 5, 9, 2]. Using a prefix sum array, how would you efficiently find the sum of elements from index 2 to 5 (inclusive)?Solution
Step 1: Understand prefix sum indexing
Prefix sum array prefix has prefix[0] = 0, prefix[i] = sum of arr[0] to arr[i-1].Step 2: Calculate sum from index 2 to 5
Sum = prefix[6] - prefix[2], because prefix[6] sums arr[0..5], prefix[2] sums arr[0..1].Final Answer:
Calculate prefix sums, then sum = prefix[6] - prefix[2] -> Option DQuick Check:
Sum of arr[2..5] = prefix[6] - prefix[2] [OK]
- Off-by-one errors in prefix indices
- Subtracting wrong prefix sums
- Confusing inclusive/exclusive ranges
Ready to prove it?
Pass the test and this pattern moves unknown
