c++data-structurestreesegment-treefenwick-tree

Can Fenwick Tree and Segment Tree in C++ perform insertions and deletions in logarithmic time?


I apologize in advance for what may be a really dumb question. I've been reading about fenwick tree and segment tree a lot recently (specific implementation of segment tree is here: https://cp-algorithms.com/data_structures/segment_tree.html#implementation) (fenwick tree example here: https://cp-algorithms.com/data_structures/fenwick.html)

But despite all my readings none of the sources seemed to talk about the time complexity for inserting and deleting an element from the tree --- only querying and updating (both takes log(n)). Am I correct in assuming that inserting and deleting an element for fenwick tree and segment tree can't be done in logn time?


Solution

  • Both Fenwick Trees and Segment Trees only work over an array of a fixed size. It's not possible to insert new elements without recomputing a large amount of the precomputed data in the tree. It's not possible to insert a new value in logarithmic time.

    Deleting however is somewhat possible if you apply a trick: you can update the element with a neutral value. E.g. if you use the data structures in order to compute sums, then you could delete an element by updating it's value to 0. If you use the data structure to compute maxima, then replace the element with negative infinity.


    If you need a data structure that allows the typical operations like query and update in logarithmic time, and additionally inserts and deletes in logarithmic time, you can take a look at the Treap data structure.