Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure to find number of elements in a given range in O(log n) time?

Tags:

c++

algorithm

stl

I'm solving a problem and I realized I am need of a data structure with following properties but cant find one even after few hours of googling. I believe STL library is too rich to not have this one hence asking here.

  1. Insert any element(should be able to contain repetetive ones) in O(log(n)) time
  2. Remove an element in O(log(n)) time as well.
  3. If i want to query for the number of elemenes in range [a,b], I should get that count in O(log(n)) time..

If I were to write it from scratch, for part 1 and 2, I would use a set or multiset and I would modify their find() method(which runs in O(log(N)) time) to return indices instead of iterators so that I can do abs(find(a)-find(b)) so I get the count of elements in log(N) time. But unfortunately for me, find() returns and iterator.

I have looked into multiset() and I could not accomplish requirement 3 in O(log(n)) time. It takes O(n).

Any hints to get it done easily?

like image 287
Anoop Avatar asked Sep 22 '15 23:09

Anoop


People also ask

Which function is used to find the total number of elements in a range?

Use the COUNT function to get the number of entries in a number field that is in a range or array of numbers. For example, you can enter the following formula to count the numbers in the range A1:A20: =COUNT(A1:A20).

What data structure should be used when number of elements is fixed?

Immutable data structures can be useful when storing a fixed collection of elements. Also, because immutable structures are more compact than mutable data structures, especially when storing a small number of elements, they are more memory efficient.

How do you determine the number of elements in an array?

//Number of elements present in an array can be calculated as follows. int length = sizeof(arr)/sizeof(arr[0]);


1 Answers

Though not part of STL, you may use Policy-Based Data Structures which are part of gcc extensions; In particular you may initialize an order statistics tree as below. The code compiles with gcc without any external libraries:

#include<iostream>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

int main()
{
    tree<int,         /* key                */
         null_type,   /* mapped             */
         less<int>,   /* compare function   */
         rb_tree_tag, /* red-black tree tag */
         tree_order_statistics_node_update> tr;

    for(int i = 0; i < 20; ++i)
        tr.insert(i);

    /* number of elements in the range [3, 10) */
    cout << tr.order_of_key(10) - tr.order_of_key(3);
}
like image 148
behzad.nouri Avatar answered Oct 10 '22 23:10

behzad.nouri