np.sqrt() for square roots in NumPy - Time & Space Complexity
We want to understand how the time to calculate square roots with numpy grows as the input size grows.
How does the work change when we give np.sqrt() bigger arrays?
Analyze the time complexity of the following code snippet.
import numpy as np
n = 10 # example size
arr = np.arange(n) # create an array from 0 to n-1
result = np.sqrt(arr) # compute square root of each element
This code creates an array of size n and finds the square root of each number in the array.
- Primary operation: Calculating the square root for each element in the array.
- How many times: Once for every element, so n times if the array has n elements.
As the array size grows, the number of square root calculations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 square root calculations |
| 100 | 100 square root calculations |
| 1000 | 1000 square root calculations |
Pattern observation: The work grows directly in proportion to the input size.
Time Complexity: O(n)
This means the time to compute square roots grows linearly with the number of elements.
[X] Wrong: "Calculating square roots with np.sqrt() takes the same time no matter how big the array is."
[OK] Correct: Each element needs its own calculation, so more elements mean more work and more time.
Understanding how numpy functions scale with input size helps you explain performance clearly and shows you know how data size affects work done.
"What if we used np.sqrt() on a 2D array instead of a 1D array? How would the time complexity change?"