np.argmin() and np.argmax() in NumPy - Time & Space Complexity
We want to understand how the time it takes to find the smallest or largest value's position in an array changes as the array gets bigger.
How does the work grow when using np.argmin() or np.argmax() on larger arrays?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.random.rand(1000)
min_index = np.argmin(arr)
max_index = np.argmax(arr)
This code creates an array of 1000 random numbers and finds the positions of the smallest and largest values.
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 once for
argminand once forargmax.
As the array size grows, the number of comparisons grows in a straight line with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 comparisons |
| 100 | About 100 comparisons |
| 1000 | About 1000 comparisons |
Pattern observation: Doubling the array size roughly doubles the work needed.
Time Complexity: O(n)
This means the time to find the smallest or largest value's position grows directly with the size of the array.
[X] Wrong: "np.argmin() or np.argmax() instantly find the answer without checking all elements."
[OK] Correct: These functions must look at every element to be sure which is smallest or largest, so they take time proportional to the array size.
Understanding how simple array scans grow with size helps you explain performance clearly and shows you know how basic operations scale in data tasks.
"What if we used np.argmin() on a 2D array with axis specified? How would the time complexity change?"