Big O of min and max in Python
What is the big O of the min
and max
functions in Python? Are they O(n)
or does Python have a better way to find the minimum and maximum of an array? If they are O(n)
, isn't it better to use a for-loop to find the desired values or do they work the same as a for-loop?
It's O(n)
. It's a general algorithm, you can't find the max/min in the general case without checking all of them. Python doesn't even have a built-in sorted collection type that would make the check easy to specialize.
A for
loop would have the same algorithmic complexity, but would run slower in the typical case, since min
/max
(on CPython anyway) are running an equivalent loop at the C layer, avoiding bytecode interpreter overhead, which the for
loop would incur.
To find the maximum or minimum of a sequence, you must look at each element once, thus you can't get better than O(n).
Of course, Python min
and max
have O(n) too: docs.
You can write your own min/max function with a for loop and it will have the same complexity, but will be slower because it is not optimized in C.