np.min() and np.max() in NumPy - Time & Space Complexity
We want to understand how the time it takes to find the smallest or largest value in data changes as the data grows.
How does the work increase when we use np.min() or np.max() on bigger arrays?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.random.rand(1000)
minimum = np.min(arr)
maximum = np.max(arr)
This code creates an array of 1000 random numbers and finds the smallest and largest values in it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning through each element of the array once to compare values.
- How many times: Each element is checked exactly one time for min and one time for max.
As the array gets bigger, the time to find min or max grows in a straight line with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 comparisons |
| 100 | About 100 comparisons |
| 1000 | About 1000 comparisons |
Pattern observation: Doubling the input size roughly doubles the work needed.
Time Complexity: O(n)
This means the time to find the minimum or maximum grows directly with the number of elements.
[X] Wrong: "np.min() or np.max() quickly finds the answer without checking all elements."
[OK] Correct: The function must look at every element to be sure of the smallest or largest value, so it takes time proportional to the array size.
Knowing how np.min() and np.max() work helps you understand basic data scanning tasks, a skill useful in many data science problems.
"What if we used np.min() on a 2D array with shape (n, m)? How would the time complexity change?"