0

I am looking for a Scala (or Java/Guava) collection that supports O(1) access to (and ideally removal of) its minimum element as well as O(log n) insertion and removal of arbitrary elements.

Thoughts?

davidrpugh
  • 4,363
  • 5
  • 32
  • 46
  • This sounds like you could do it by wrapping a `TreeSet` with an extra pointer to the minimum element so that after every insertion or removal (already O(log n)) you updated the current minimum element (O(log n) to query). – Louis Wasserman Mar 21 '16 at 21:58
  • 1
    I think, you are looking for `PriorityQueue`: http://www.scala-lang.org/api/current/#scala.collection.mutable.PriorityQueue – Dima Mar 21 '16 at 22:11
  • 1
    [This page](http://docs.scala-lang.org/overviews/collections/performance-characteristics.html) is a good place to start when considering the performance characteristics of Scala collections. – jwvh Mar 21 '16 at 22:16
  • @jwvh No `PriorityQueue` there though ... shame ;) – Dima Mar 21 '16 at 22:17
  • @Dima, well I _did_ say it was only a place to _start_. That page probably could use a good update. – jwvh Mar 21 '16 at 22:22
  • I don't think you can get O(1) removal, but `PriorityQueue` has O(1) min element (`head`). And insert / removal seem to be `O(log(n))` from a quick look at the source – The Archetypal Paul Mar 21 '16 at 22:22

2 Answers2

5

PriorityQueue:

Implementation note: this implementation provides O(log(n)) time for the enqueuing and dequeuing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size).

This class is a member of the Java Collections Framework.

Community
  • 1
  • 1
mfulton26
  • 29,956
  • 6
  • 64
  • 88
  • I considered PriorityQueue but because the backing store is implemented using a heap there is no way to get O(log n) `remove(Object)` which I would like. – davidrpugh Mar 22 '16 at 09:22
-1

Create your own collection backed by ArrayList. It needs additional fields minimum element and position of minimum element. Update those fields when you add element if that element is new minimum.

celezar
  • 442
  • 3
  • 9