5

Is it O(1) or O(logN) but with a smaller coefficient?

If this is unspecified, I'd at least like to know the answer based on a reasonable supposition that the map/set is implemented using a red-black or AVL tree. The general algorithm to insert an element, I think, is something like:

  • find the right place - O(logN)
  • do the actual insertion - ?
  • rebalance the tree if necessary - ?

Now if we provide the correct iterator hint, then the first step becomes O(1). Are the other steps also O(1) or O(logN)?

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • Think about it. What steps would you do if you were writing the insertion method? What steps would you do if you needed to rebalance the tree? Are the steps dependent on the number of nodes? – George Houpis Dec 11 '14 at 14:44
  • 1
    Here's a bunch of answers that could be helpful: [stl-map-performance](http://stackoverflow.com/questions/10165708/stl-map-performance), [why-is-stdmap-implemented-as-red-black-tree](http://stackoverflow.com/questions/5288320/why-is-stdmap-implemented-as-red-black-tree), [difference-between-red-black-trees-and-avl-trees](http://stackoverflow.com/questions/16257761/difference-between-red-black-trees-and-avl-trees) – nouney Dec 11 '14 at 14:48

3 Answers3

5

The standard doesn't say how the containers are to be implemented, so you can't count on an RB or a AVL tree. In practice... the complexity constraints are such that I don't know of any other implementations which would fit the bill. But it's in the complexity constraints that you will find the answer: “logarithmic in general, but amortized constant if t is inserted right before p.” So if the hint is correct, the implementation must be such that the insertion is O(1).

James Kanze
  • 150,581
  • 18
  • 184
  • 329
2
  • find the right place - O(logN)
  • do the actual insertion - O(1), no matter if it is a AVL or RB tree
  • rebalance the tree if necessary - I don't know the exact BIG-O notation for the AVL tree, but for a RB tree it is O(1).

With an iterator hint, the step #2 (insertion) and step #3 (rebalance) are not impacted. By providing an iterator, you're just doing the step #1 ("find the right place") by yourself, the general complexity is the same.

nouney
  • 4,363
  • 19
  • 31
0

First standard never said exactly what kind of data structure it uses to implement set. It's just the complexity of operations on them which help us direct towards some sort of self-balanced binary search tree.

Yes, if you provide correct hint to insert by placing right iterator, then all steps would be amortized O(1) as step 2 and 3 and not dependent on anything.

ravi
  • 10,994
  • 1
  • 18
  • 36