Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of min, max on sets

Tags:

python

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!

like image 700
abadawi Avatar asked Mar 11 '18 05:03

abadawi


1 Answers

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.

like image 91
Shivam Tripathi Avatar answered Sep 29 '22 03:09

Shivam Tripathi