keywords: C++, Time Complexity, Vector, Set and Map

Time complexity of find() in std::map

std::map and std::set are implemented by compiler vendors using highly balanced binary search trees (e.g. red-black tree, AVL tree).

As correctly pointed out by David, find would take O(log n) time, where n is the number of elements in the container.

But that’s with primitive data types like int, long, char, double etc., not with strings.

If std:string, lets say of size ’m’, is used as key, traversing the height of the balanced binary search tree will require log n comparisons of the given key with an entry of the tree.

When std::string is the key of the std::map or std::set, find and insert operations will cost O(m log n), where m is the length of given string that needs to be found.

Quoted From:
Time complexity of find() in std::map?

Time complexity of find() in std::vector, std::map and std::unordered_map

The time complexity to find an element in `std::vector` by linear search is O(N). It is O(log N) for `std::map` and O(1) for `std::unordered_map`. However, the complexity notation ignores constant factors. Different containers have various traversal overheads to find an element. For example, node branching during tree traversals in std::set and hashing complexity in std::unordered_set are considered constant overheads in complexity. On the other hand, although the complexity of std::vector is linear, the memory addresses of elements in std::vector are contiguous, which means it is faster to access elements in order.

Quoted From:
Searching: vector, set and unordered_set


Searching: vector, set and unordered_set

Time complexity

File:Comparison computational complexity.svg

Perhaps this is what the stories meant when they called somebody heartsick. Your heart and your stomach and your whole insides felt empty and hollow and aching. ― Gabriel García Márquez