np.abs() for absolute values in NumPy - Time & Space Complexity
We want to understand how the time to find absolute values changes as the input array grows.
How does the work increase when we have more numbers to process?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.array([-3, 1, -7, 4, -2])
abs_arr = np.abs(arr)
print(abs_arr)
This code creates an array and finds the absolute value of each element.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calculating absolute value for each element in the array.
- How many times: Once for each element in the array.
As the array gets bigger, the number of absolute value calculations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 absolute value calculations |
| 100 | 100 absolute value calculations |
| 1000 | 1000 absolute value calculations |
Pattern observation: The work grows directly with the number of elements.
Time Complexity: O(n)
This means the time to compute absolute values grows in a straight line as the input size grows.
[X] Wrong: "np.abs() runs in constant time no matter the array size."
[OK] Correct: The function must check each element, so more elements mean more work.
Understanding how simple array operations scale helps you explain performance clearly and confidently.
"What if we used np.abs() on a 2D array instead of 1D? How would the time complexity change?"