Big O of min and max in Python
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.
For time complexity O(1) You can use this:
minimum = y ^ ((x ^ y) & -(x < y)); // min(x, y)
maximum = x ^ ((x ^ y) & -(x < y)); // max(x, y)
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.