np.linspace() for evenly spaced arrays in NumPy - Time & Space Complexity
We want to understand how the time to create evenly spaced numbers with np.linspace() changes as we ask for more points.
How does the work grow when the number of points increases?
Analyze the time complexity of the following code snippet.
import numpy as np
points = np.linspace(0, 10, num=1000)
This code creates 1000 numbers evenly spaced between 0 and 10.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calculating each point's value by dividing the interval and placing points.
- How many times: Once for each of the requested points (num times).
Each point requires a calculation, so the total work grows directly with the number of points.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calculations |
| 100 | About 100 calculations |
| 1000 | About 1000 calculations |
Pattern observation: Doubling the number of points roughly doubles the work.
Time Complexity: O(n)
This means the time to create the array grows linearly with the number of points requested.
[X] Wrong: "np.linspace() runs in constant time no matter how many points I ask for."
[OK] Correct: Each point must be calculated and stored, so more points mean more work and more time.
Understanding how array creation scales helps you reason about performance when working with large datasets or simulations.
"What if np.linspace() returned a generator instead of an array? How would the time complexity change?"