Now. The problem was that this code was judged TLE for, seemingly, no reason at all! Having lost thirty minutes trying to understand where my complexity analysis skills failed, in desperation, I replaced multiset with an ordinary :

and it passed! But I was still a bit salty, so I tried to figure out why did this happen: clearly there is something wrong with multiset.

First of all, insertion and searching in and is the same since they both internally implemented as Red-Black trees. The only thing that is nor the first nor the second is the method in the first snippet. So, this must be the reason why the code failed.

At that point, I've dived into the source code of the . The headers for it on Unix machine should be located at , where is the version of the compiler (run to get it). There we can see , and files among many. yields

Red-Black tree. Its definition is contained within with the true method . At this point, we really have to look at the source code. Conveniently, has a GitHub repository (kind of) and the corresponding file that implements is . The following is the implementation of of :

Ignoring all these scary looking templates, we can see that the method is just three lines long! Namely, in the first line, we get a pair of two iterators, first of which points to the first element in the set with its key equal to and the second — to the last. In the second line, we use to count elements between the first and the last element points to. Since is a balanced binary search tree, we know that if we commit DFS through the tree and write out the nodes in the order of traversal, we will get a sorted sequence. What does is just consequently iterates from forward and onward until reaches . Since we know that between them are the nodes with the same key, this counting will yield us their total number.

So... std::distance has linear time complexity! It jumps between different locations in memory step-by-step until reaching the "terminal" node. Basically, there's no other way to count nodes within the tree (Although, I know that you can (somehow) invoke custom instance of internal tree data structure that will be able to accompany each node with a subtree's field, which can be used to bring down the complexity of up to but I need clarification on this).

The only difference between and is that does not depend on the uniqueness of the nodes. Look at these two excerpts from the source code:

Oops! Actually... Wow, I didn't know that my inattentiveness can be that hight of a level. Because I read the very same article on cppreference and tried to find complexity analysis. But because I failed, I started to mess with source files. I guess, sometimes happens :-)