Prefix Sum Array in DSA Javascript - Time & Space Complexity
We want to understand how fast we can build and use a prefix sum array.
How does the time needed change as the input array grows?
Analyze the time complexity of the following code snippet.
const prefixSum = (arr) => {
const prefix = [];
prefix[0] = arr[0];
for (let i = 1; i < arr.length; i++) {
prefix[i] = prefix[i - 1] + arr[i];
}
return prefix;
};
This code creates a prefix sum array where prefix[i] is the sum of all elements from arr[0] to arr[i] inclusive.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop that adds the current element to the previous sum.
- How many times: The loop runs once for each element after the first, so (n - 1) times.
As the input array gets bigger, the number of additions grows roughly the same as the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 9 additions |
| 100 | 99 additions |
| 1000 | 999 additions |
Pattern observation: The operations increase linearly as the input size increases.
Time Complexity: O(n)
This means the time to build the prefix sum grows directly with the size of the input array.
[X] Wrong: "Since we add sums repeatedly, the time is quadratic O(n²)."
[OK] Correct: Each addition uses the previous sum, so we do only one addition per element, not repeated sums for each element.
Knowing prefix sums and their time complexity helps you quickly answer range sum queries efficiently, a common skill interviewers look for.
"What if we needed to build the prefix sum array multiple times for different input arrays? How would that affect the overall time complexity?"
Practice
arr?Solution
Step 1: Understand prefix sum array 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 from the start up to that index inarr. correctly describes this sum accumulation behavior.Final Answer:
An array where each element is the sum of all elements from the start up to that index in arr. -> Option AQuick Check:
Prefix sum = cumulative sum [OK]
- Confusing prefix sum with product or max
- Thinking prefix sum stores differences
- Assuming prefix sum stores original values
prefix for an input array arr?Solution
Step 1: Check initialization of prefix sum array
Prefix sum starts with first element of arr, so prefix[0] = arr[0].Step 2: Verify loop logic for prefix sums
Each prefix[i] = prefix[i-1] + arr[i] correctly accumulates sums.Final Answer:
const prefix = [arr[0]]; for(let i=1; i<arr.length; i++) { prefix[i] = prefix[i-1] + arr[i]; } -> Option CQuick Check:
Initialize with arr[0], then add previous prefix [OK]
- Starting prefix with 0 instead of arr[0]
- Using multiplication instead of addition
- Accessing prefix[-1] which is undefined
const arr = [2, 4, 6, 8];
const prefix = [arr[0]];
for(let i = 1; i < arr.length; i++) {
prefix[i] = prefix[i-1] + arr[i];
}
console.log(prefix);Solution
Step 1: Calculate prefix sums step-by-step
prefix[0] = 2; prefix[1] = 2 + 4 = 6; prefix[2] = 6 + 6 = 12; prefix[3] = 12 + 8 = 20.Step 2: Confirm final prefix array
The prefix array is [2, 6, 12, 20].Final Answer:
[2, 6, 12, 20] -> Option DQuick Check:
Sum accumulates correctly [OK]
- Adding elements incorrectly or skipping first element
- Confusing prefix array with original array
- Off-by-one errors in loop
const arr = [1, 3, 5, 7];
const prefix = [];
for(let i = 0; i < arr.length; i++) {
prefix[i] = prefix[i-1] + arr[i];
}
console.log(prefix);Solution
Step 1: Analyze prefix[-1] usage at i=0
At i=0, prefix[i-1] is prefix[-1], which is undefined, causing NaN result.Step 2: Fix initialization to avoid undefined
Initialize prefix[0] = arr[0] before loop or handle i=0 separately.Final Answer:
prefix array is not initialized with first element, causing prefix[-1] to be undefined. -> Option AQuick Check:
Accessing prefix[-1] causes undefined [OK]
- Starting loop at 0 without initializing prefix[0]
- Ignoring undefined prefix[-1] access
- Assuming prefix[-1] is zero automatically
arr = [3, 1, 4, 1, 5], how can you use a prefix sum array to efficiently find the sum of elements between indices 1 and 3 (inclusive)?Solution
Step 1: Build prefix sum array for arr
prefix = [3, 4, 8, 9, 14] where prefix[i] = sum of arr[0..i].Step 2: Calculate sum from index 1 to 3
Sum = prefix[3] - prefix[0] = 9 - 3 = 6 (elements 1,4,1).Final Answer:
Calculate prefix sums, then subtract prefix[0] from prefix[3]. -> Option BQuick Check:
Sum(1 to 3) = prefix[3] - prefix[0] [OK]
- Subtracting prefix[i] instead of prefix[i-1]
- Using wrong indices for subtraction
- Not building prefix sums first
Ready to prove it?
Pass the test and this pattern moves unknown
