Comparison operations in NumPy - Time & Space Complexity
We want to understand how long it takes to compare values in numpy arrays as the array gets bigger.
How does the time needed grow when we check many numbers?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.random.randint(0, 100, size=1000)
result = arr > 50
This code creates an array of 1000 random numbers and compares each number to 50, producing a True/False array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing each element in the array to the number 50.
- How many times: Once for every element in the array, so 1000 times here.
When the array size grows, the number of comparisons grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: The number of comparisons grows directly with the number of elements.
Time Complexity: O(n)
This means the time to compare grows in a straight line with the number of items.
[X] Wrong: "Comparing all elements is faster because numpy is optimized, so it's almost constant time."
[OK] Correct: Even though numpy is fast, it still checks each element once, so time grows with array size.
Knowing how comparison time grows helps you explain performance when working with big data arrays.
"What if we compare two arrays element-wise instead of one array to a number? How would the time complexity change?"