# How to get all in constant time?

We are planning to design a system where following operations are supported.

Increment("foo"): Increase the count of key 'foo'

Decrement("bar"): Decrease the count of key 'bar'

getMin():  Return the key which has minimum count

getMax():  Return the key which has maximum count


The catch is all operations should be in $O(1)$ time.

• Fibonacci heaps support all your operations in $O(1)$ amortized running time (you need to maintain two heaps, one for getMin and one for getMax). The Wikipedia page describes several other heaps which have $O(1)$ worst case running time for all these operations. – Yuval Filmus Sep 10 '18 at 6:49
• Without something not bounded by a constant, there is no point in asymptotic analysis. Be explicit, don't make your readers guess there can be $n$ keys. – greybeard Sep 12 '18 at 8:16

If your keys are strings, you can use a prefix tree mapping keys to values. In this way each operation can be implemented in $O(h)$ time, where $h$ is the length of the key, which means it is $O(1)$ to the size of the collection.
To get the minimum key(or maximum) you can traverse the tree, by going through the edge from the lexicographically smallest (or largest if you need max) node on each level.
I don't think you can get better complexity than $O(h)$ for arbitrary sized keys as you need $O(h)$ time to output the key anyway.

• We can't assume key is constant size. How will you get min/max in constant time? – rgaut Sep 10 '18 at 21:34
• @rgaut If the key isn't constant size, can't possibly return the min or max key in constant time, so you're sunk. – David Richerby Oct 11 '18 at 18:31
• @rgaut You could hash each key to obtain a fixed length value to use as the input to all the operations. – RandomPerfectHashFunction Aug 8 '19 at 18:02