np.arange() for range arrays in NumPy - Time & Space Complexity
We want to understand how the time to create arrays with np.arange() changes as the size of the array grows.
How does the work needed grow when we ask for bigger ranges?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.arange(0, n, 1)
This code creates a NumPy array starting at 0 up to (but not including) n, stepping by 1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Filling each element of the array with a value from 0 to n-1.
- How many times: Exactly n times, once for each element.
As n grows, the number of operations grows directly with n because each element must be set.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The operations grow in a straight line with the input size.
Time Complexity: O(n)
This means the time to create the array grows directly in proportion to the number of elements requested.
[X] Wrong: "Creating an array with np.arange() is instant and does not depend on size."
[OK] Correct: Even though np.arange() is fast, it still needs to fill each element, so time grows with the number of elements.
Understanding how array creation scales helps you reason about data preparation steps in real projects and interviews.
What if we changed the step size from 1 to 2? How would the time complexity change?