np.full() for custom-filled arrays in NumPy - Time & Space Complexity
We want to understand how the time needed to create an array filled with a specific value changes as the array size grows.
How does the work increase when we ask numpy to fill bigger arrays?
Analyze the time complexity of the following code snippet.
import numpy as np
# Create a 1D array of size n filled with the value 7
n = 1000
arr = np.full(n, 7)
This code creates a numpy array of length n, filling every element with the number 7.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Filling each element of the array with the given value.
- How many times: Exactly once for each element, so
ntimes.
As the array size grows, the time to fill it grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 fill operations |
| 100 | 100 fill operations |
| 1000 | 1000 fill operations |
Pattern observation: Doubling the size doubles the work needed to fill the array.
Time Complexity: O(n)
This means the time to create and fill the array grows linearly with the number of elements.
[X] Wrong: "np.full() fills the array instantly regardless of size because it uses a shortcut."
[OK] Correct: Even though numpy is fast, it must still set each element, so time grows with array size.
Understanding how array creation scales helps you reason about data preparation speed, a key skill in data science and coding interviews.
What if we changed np.full() to create a 2D array of size n by m? How would the time complexity change?