min, max have O(N) time complexity because they have to loop over the given list/string and check every index to find min/max. But I am wondering what would be the time complexity of min,max if used on a set? For example:
s = {1,2,3,4} # s is a set
using min/max we get:
min(s) = 1
max(s) = 4
Since sets do not use indices like lists and strings, but instead operate using buckets that can be accessed directly, does the time complexity of min/max differ than the general case?
Thank you!
As pointed out in the comments above, python is a well documented language and one must always refer to the docs first.
Answering the question, according to the docs,
A set object is an unordered collection of distinct hashable objects.
Being unordered means that to evaluate maximum or minimum among all the elements using any means (inbuilt or not) would at least require one to look at each element, which means O(n) complexity at best.
On top of it, max and min functions of python iterate over each element and are O(n) in all cases. You can always look up the source code yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With