Prefix Sum Array in DSA Python - Time & Space Complexity
We want to understand how fast we can build and use a prefix sum array.
How does the time needed grow as the input array gets bigger?
Analyze the time complexity of the following code snippet.
def prefix_sum(arr):
n = len(arr)
prefix = [0] * n
prefix[0] = arr[0]
for i in range(1, n):
prefix[i] = prefix[i-1] + arr[i]
return prefix
# Example usage:
# arr = [1, 2, 3, 4]
# prefix_sum(arr) returns [1, 3, 6, 10]
This code creates a new array where each element is the sum of all elements up to that position in the original array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single for-loop that adds elements one by one.
- 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 size of the array.
| 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 array grows in direct proportion to the size of the input array.
[X] Wrong: "Since we add numbers repeatedly, the time must be quadratic O(n²)."
[OK] Correct: Each addition uses the previous sum, so we only do one addition per element, not a sum over all previous elements each time.
Knowing how prefix sums work and their time cost helps you solve many problems efficiently, like range sums or frequency counts.
"What if we wanted to build a 2D prefix sum array for a matrix? How would the time complexity change?"
Practice
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 from the start up to that index inarr. correctly describes this sum accumulation; others describe different operations.Final Answer:
An array where each element is the sum of all elements from the start up to that index in arr. -> Option DQuick Check:
Prefix sum = cumulative sum [OK]
- Confusing prefix sum with product or max operations
- Thinking prefix sum stores differences
- Assuming prefix sum stores original array values
prefix for an input list arr?Solution
Step 1: Analyze code for prefix sum logic
prefix = [arr[0]] for i in range(1, len(arr)): prefix.append(prefix[i-1] + arr[i]) starts prefix with first element and adds current element to previous prefix sum correctly.Step 2: Check other options for errors
prefix = [] for i in range(len(arr)): prefix.append(arr[i] + arr[i-1]) adds current and previous array elements incorrectly; C multiplies instead of sums; A subtracts instead of sums.Final Answer:
prefix = [arr[0]]\nfor i in range(1, len(arr)):\n prefix.append(prefix[i-1] + arr[i]) -> Option CQuick Check:
Prefix sum uses cumulative addition [OK]
- Using multiplication instead of addition
- Adding wrong elements or indices
- Initializing prefix array incorrectly
arr = [3, 1, 4, 1, 5]
prefix = [arr[0]]
for i in range(1, len(arr)):
prefix.append(prefix[i-1] + arr[i])
print(prefix)Solution
Step 1: Calculate prefix sums step-by-step
Start with prefix = [3]. Then add 1: 3+1=4, add 4: 4+4=8, add 1: 8+1=9, add 5: 9+5=14.Step 2: Form the final prefix array
prefix = [3, 4, 8, 9, 14]Final Answer:
[3, 4, 8, 9, 14] -> Option AQuick Check:
Sum accumulates correctly [OK]
- Confusing prefix array with original array
- Off-by-one errors in indexing
- Incorrect initial prefix value
arr = [2, 4, 6]
prefix = [0]
for i in range(len(arr)):
prefix.append(prefix[i] + arr[i])
print(prefix)Solution
Step 1: Identify initialization and loop issues
Initializing prefix with [0] and looping from 0 adds an extra leading zero. Tracing: i=0 append(0+2)=2 -> [0,2]; i=1 append(2+4)=6 -> [0,2,6]; i=2 append(6+6)=12 -> [0,2,6,12]. This produces prefix sums of length n+1 with prefix[0]=0, whereas standard is length n starting from arr[0].Step 2: Correct initialization and loop range
Start prefix with first element arr[0], then loop from index 1 to end to add sums correctly.Final Answer:
Change prefix = [0] to prefix = [arr[0]] and loop from 1 to len(arr)-1. -> Option AQuick Check:
Proper start and loop fix prefix sums [OK]
- Starting prefix with zero instead of first element
- Looping from zero causing off-by-one errors
- Using wrong prefix index inside loop
arr of length n, how can you use a prefix sum array to find the sum of elements between indices l and r (inclusive) efficiently?Solution
Step 1: Understand prefix sum usage for range sums
Prefix sum at index r stores sum from start to r. To get sum from l to r, subtract sum from start to l-1.Step 2: Handle edge case when l is zero
If l is zero, sum is prefix[r] directly since no subtraction needed.Final Answer:
Calculate sum as prefix[r] - prefix[l-1] if l > 0, else prefix[r]. -> Option BQuick Check:
Range sum = prefix[r] - prefix[l-1] [OK]
- Adding prefix sums instead of subtracting
- Ignoring edge case when l = 0
- Using multiplication or looping unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
