Middle
What is the asymptotic complexity of operations performed with unordered_set and set containers in C++?
sobes.tech AI
Answer from AI
For std::set (based on a balanced binary search tree):
- Insertion (
insertof one element): O(log N) - Deletion (
eraseof one element): O(log N) - Search (
find): O(log N)
For std::unordered_set (based on a hash table):
- Average:
- Insertion (
insertof one element): O(1) - Deletion (
eraseof one element): O(1) - Search (
find): O(1)
- Insertion (
- Worst case (with severe hash collisions):
- Insertion (
insertof one element): O(N) - Deletion (
eraseof one element): O(N) - Search (
find): O(N)
- Insertion (
Comparison table:
| Operation | std::set |
std::unordered_set (average) |
std::unordered_set (worst case) |
|---|---|---|---|
| Insert single element | O(log N) | O(1) | O(N) |
| Remove single element | O(log N) | O(1) | O(N) |
| Search single element | O(log N) | O(1) | O(N) |