np.sign() for sign detection in NumPy - Time & Space Complexity
We want to understand how the time to find the sign of numbers grows as we have more numbers.
How does the work change when the input array gets bigger?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.array([-3, 0, 4, -1, 5])
signs = np.sign(arr)
print(signs)
This code finds the sign (-1, 0, or 1) of each number in the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the sign of each element in the array.
- How many times: Once for each element in the input array.
As the number of elements grows, the time to check signs grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 sign checks |
| 100 | About 100 sign checks |
| 1000 | About 1000 sign checks |
Pattern observation: The work grows directly with the number of elements.
Time Complexity: O(n)
This means the time to find signs grows in a straight line as the input size grows.
[X] Wrong: "np.sign() checks all elements multiple times, so it is slower than linear."
[OK] Correct: np.sign() only looks at each element once, so it runs in linear time, not slower.
Understanding how simple array operations scale helps you explain performance clearly and confidently.
"What if we used np.sign() on a 2D array instead of 1D? How would the time complexity change?"