Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complexity of set::insert

Tags:

I have read that insert operation in a set takes only log(n) time. How is that possible?

To insert, first we have find the location in the sorted array where the new element must sit. Using binary search it takes log(n). Then to insert in that location, all the elements succeeding it should be shifted one place to the right. It takes another n time.

My doubt is based on my understanding that set is implemented as an array and elements are stored in sorted order. Please correct me if my understanding is wrong.

like image 365
bibbsey Avatar asked Oct 08 '12 06:10

bibbsey


People also ask

What is the complexity of set?

Set is implemented as a balanced tree structure that is why it is possible to maintain order between the elements (by specific tree traversal). The time complexity of set operations is O(log n) while for unordered_set, it is O(1).

What is the complexity of different std :: set operations?

std::set is commonly implemented as a red-black binary search tree. Insertion on this data structure has a worst-case of O(log(n)) complexity, as the tree is kept balanced.

What is the time complexity of set C++?

Generally, The time complexity of operations like insertion and deletion in the set in C++ is O ( l o g n ) O(log n) O(logn).

Is adding to a set O 1?

add() function is O(1) because Python's set data structure is implemented as a hash table and you can expect lookup, insert, and delete operations to have constant runtime complexity.


1 Answers

std::set is commonly implemented as a red-black binary search tree. Insertion on this data structure has a worst-case of O(log(n)) complexity, as the tree is kept balanced.

like image 160
cdhowie Avatar answered Sep 18 '22 20:09

cdhowie