np.zeros() for zero-filled arrays in NumPy - Time & Space Complexity
We want to understand how the time to create a zero-filled array changes as the array size grows.
How does the work needed grow when we ask for bigger arrays filled with zeros?
Analyze the time complexity of the following code snippet.
import numpy as np
n = 1000
zero_array = np.zeros(n)
This code creates a one-dimensional array of length n filled with zeros.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Filling each element of the array with zero.
- How many times: Once for each element, so
ntimes.
As the array size grows, the time to fill it with zeros grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 zero assignments |
| 100 | About 100 zero assignments |
| 1000 | About 1000 zero assignments |
Pattern observation: Doubling the size roughly doubles the work needed.
Time Complexity: O(n)
This means the time to create the zero-filled array grows linearly with the number of elements.
[X] Wrong: "Creating a zero array is instant and does not depend on size."
[OK] Correct: Even though zeros are simple, the system must still assign zero to each element, so bigger arrays take more time.
Knowing how array creation time grows helps you understand performance when working with large data in real projects.
"What if we create a 2D zero array with shape (n, n)? How would the time complexity change?"