np.ones() for one-filled arrays in NumPy - Time & Space Complexity
We want to understand how the time to create an array filled with ones changes as the array size grows.
How does the work needed grow when we ask for bigger arrays?
Analyze the time complexity of the following code snippet.
import numpy as np
n = 1000
ones_array = np.ones(n)
This code creates a one-dimensional array of length n filled with ones.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Filling each element of the array with the value 1.
- How many times: Once for each element, so
ntimes.
As the array size n grows, the time to fill the array grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the size of the array.
Time Complexity: O(n)
This means the time to create the array grows in a straight line with the number of elements.
[X] Wrong: "Creating an array with np.ones() takes the same time no matter the size."
[OK] Correct: The function must fill each element, so bigger arrays take more time.
Understanding how array creation scales helps you reason about data preparation steps in real projects.
What if we changed np.ones(n) to np.ones((n, n))? How would the time complexity change?