np.count_nonzero() for counting in NumPy - Time & Space Complexity
We want to understand how the time to count non-zero elements grows as the array gets bigger.
How does the work change when the input size increases?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.random.randint(0, 5, size=1000)
count = np.count_nonzero(arr)
This code creates an array of 1000 numbers and counts how many are not zero.
- Primary operation: Checking each element to see if it is non-zero.
- How many times: Once for every element in the array.
As the array size grows, the number of checks grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of elements.
Time Complexity: O(n)
This means the time to count non-zero elements grows in a straight line with the array size.
[X] Wrong: "Counting non-zero elements is instant no matter the array size."
[OK] Correct: The function must look at each element once, so bigger arrays take more time.
Knowing how counting operations scale helps you explain efficiency clearly and shows you understand how data size affects performance.
"What if we count non-zero elements only in a slice of the array? How would the time complexity change?"