Boolean type in NumPy - Time & Space Complexity
We want to understand how fast operations with Boolean arrays run in numpy.
How does the time needed change when the array gets bigger?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.random.choice([True, False], size=1000)
result = np.sum(arr)
This code creates a Boolean array and counts how many True values it has.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element in the Boolean array to count True values.
- How many times: Once for every element in the array.
As the array gets bigger, the time to count True values grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: Doubling the array size doubles the work needed.
Time Complexity: O(n)
This means the time grows directly with the number of elements in the array.
[X] Wrong: "Counting True values is instant and does not depend on array size."
[OK] Correct: The code must check each element once, so bigger arrays take more time.
Knowing how Boolean operations scale helps you explain performance clearly and shows you understand data handling basics.
"What if we used a numpy function that stops early when a True is found? How would the time complexity change?"