Timeline
timeline
2025-09-15
init
unordered_map and unordered_set achieves O(n) lookup
Problem:
Initially used brute force search, but got TLE, as follows
1 |
|
Using hash table lookup reduces from O(n^2) to O(n), below is the officially recommended C++ implementation
1 |
|
Average time complexity
| Operation | unordered_set | unordered_map |
|---|---|---|
| Insert | O(1) | O(1) |
| Search | O(1) | O(1) |
| Delete | O(1) | O(1) |
- HereO(1)isAverage complexity, assuming the hash function is evenly distributed and collisions are few.
- Main advantages:Faster than std::set/std::map (based on red-black tree), red-black tree lookup is O(log n).
Worst-case time complexity
- In the worst case, if all elements are hashed to the same bucket (hash collision), it degenerates intolinked list:
- lookup, insertion, deletion all becomeO(n)。
- C++ standard library implementations typically usebucket + linked list (or red-black tree), when there are too many collisions, the linked list is converted into a red-black tree, thus reducing the worst-case complexity:
- After C++11, unordered_map/unordered_set’s single bucket linked list length exceeds a certain threshold (usually 8), it will be converted into a red-black tree, ensuring worst-case complexityO(log n)。
Space complexity
- Average O(n), storing hash table and elements.
- Hash table requires an extra bucket array, occupying extra space.
