0

Java has multiset, and SmallTalk has a Bag class, and they are said to be the same function: keep a set of values but allow multiple values (with a count for each).

But seems like multiset can be implemented by a hash table that keeps counts on the keys (or maybe there are other possible implementations).

Do some implementation of multisets or bags offer better time complexity than the hash above? The required operations can be

  1. insert item
  2. delete item
  3. get the minimum value in the set
  4. get the maximum value in the set

In particular, I am hoping that for each of the 4 operations above, it can be done better than O(n), possibly all O(log n) or better. (the 3 and 4 above is expected to be O(log n) only if the multiset is maintained in some sorted way whenever a value is added or removed from it.)

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

1 Answers1

0

It depends if the Multiset is implemented by a hastable or a sorted set.

For a hashtable, the insert/update operations are O(1) (min and max are O(n)), but the downside is that a hashtable doesn't keep the elements in order. Furthermore, this requires that for each element to be stored, it is possible to compute a consistent hash value.

For a sorted set, all operations are O(log n), but with the upside that the elements are kept in sorted order (hence, it is efficient in reporting ranges of elements). This requires that each element to be stored is comparable (i.e. an ordering exists over the elements).

Leon Bouquiet
  • 4,159
  • 3
  • 25
  • 36
  • for hash table, isn't inserting or removing `O(1)` while getting the minimum or maximum value `O(n)`? If it is a sorted set... what data structure will that be? If it is an array, then inserting can be `O(n)` – nonopolarity Nov 09 '12 at 09:02
  • Whoops, you're right, I meant to say O(1) instead of O(n). I corrected this, thanks :) – Leon Bouquiet Nov 09 '12 at 09:04