np.cumsum() for cumulative sum in NumPy - Time & Space Complexity
We want to understand how the time taken by np.cumsum() changes as the input array grows.
Specifically, how does the work increase when the array gets bigger?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
cum_sum = np.cumsum(arr)
print(cum_sum)
This code calculates the cumulative sum of the array elements, producing a new array where each element is the sum of all previous elements including itself.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each element to a running total to build the cumulative sum.
- How many times: Once for each element in the array, from start to end.
As the array size grows, the number of additions grows in a straight line with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows evenly as the input size increases; doubling the input doubles the work.
Time Complexity: O(n)
This means the time to compute the cumulative sum grows directly in proportion to the number of elements.
[X] Wrong: "Since cumulative sum involves sums of sums, it must take much longer than just adding all elements once."
[OK] Correct: The function cleverly adds each element only once in order, so it does not repeat sums unnecessarily.
Understanding how simple array operations scale helps you explain and optimize data processing tasks clearly and confidently.
"What if we computed cumulative sums on a 2D array along one axis? How would the time complexity change?"
Practice
np.cumsum() function do when applied to a 1D numpy array?Solution
Step 1: Understand the function purpose
np.cumsum()adds elements cumulatively, meaning each element is the sum of all previous elements plus itself.Step 2: Compare with other options
Options B, C, and D describe different operations: product, sorting, and max value, which are not whatnp.cumsum()does.Final Answer:
Calculates the cumulative sum of the elements step by step -> Option AQuick Check:
np.cumsum() = cumulative sum [OK]
- Confusing cumulative sum with product
- Thinking it sorts the array
- Assuming it finds max or min values
arr?Solution
Step 1: Check numpy function usage
np.cumsum(arr)is the basic syntax to get cumulative sum of all elements in the array.Step 2: Check array method and axis parameter
arr.cumsum()is a valid method call on numpy arrays. Also,np.cumsum(arr, axis=0)computes cumulative sum along the first axis, valid for multi-dimensional arrays.Final Answer:
np.cumsum(arr) -> Option AQuick Check:
Basic syntax is np.cumsum(arr) [OK]
- Thinking only np.cumsum(arr) works
- Ignoring axis parameter for multi-dimensional arrays
- Assuming cumsum is not an array method
import numpy as np arr = np.array([2, 4, 6, 8]) cum_sum = np.cumsum(arr) print(cum_sum)
Solution
Step 1: Calculate cumulative sums stepwise
Start with 2, then 2+4=6, then 6+6=12, then 12+8=20.Step 2: Form the cumulative sum array
The resulting array is [2, 6, 12, 20].Final Answer:
[2 6 12 20] -> Option CQuick Check:
Running total sums = [2, 6, 12, 20] [OK]
- Confusing cumulative sum with original array
- Adding elements incorrectly
- Reversing the order of sums
import numpy as np arr = np.array([[1, 2], [3, 4]]) cum_sum = np.cumsum(arr, axis=2) print(cum_sum)
Solution
Step 1: Check array dimensions
The array has shape (2, 2), so it has axes 0 and 1 only.Step 2: Validate axis parameter
Using axis=2 is invalid because axis 2 does not exist for this 2D array, causing an error.Final Answer:
Axis 2 does not exist for a 2D array -> Option DQuick Check:
Axis must be within array dimensions [OK]
- Assuming axis parameter is optional but invalid
- Thinking cumsum only works on 1D arrays
- Confusing syntax error with axis error
sales = np.array([[5, 3, 2],
[4, 6, 1],
[7, 2, 3],
[3, 5, 4]])Which code correctly computes the cumulative sales per product over the days?
Solution
Step 1: Understand the array shape and axis meaning
The array shape is (4, 3): 4 days (rows), 3 products (columns). Axis 0 moves down rows (days), axis 1 moves across products.Step 2: Choose axis for cumulative sum per product over days
To get cumulative sales per product over days, sum down each column (axis=0).Final Answer:
np.cumsum(sales, axis=0) -> Option BQuick Check:
Cumulative sum down rows = axis 0 [OK]
- Using axis=1 sums across products, not over days
- Ignoring axis parameter
- Using invalid axis=2 for 2D array
Ready to prove it?
Pass the test and this pattern moves unknown
