All O(1) Data Structure
Count string keys up and down, and read a key with the highest or lowest count, each in constant time.
Design a class that keeps a count for each string key and supports four operations. Each one must run in O(1) time, meaning a fixed amount of work however many keys are stored:
: add 1 to the key's count. A key that is not stored yet is added with count 1.inc(key) : subtract 1 from the key's count. When the count reaches 0, the key is removed.dec(key) : return a key with the highest count, orgetMaxKey() when no keys are stored."" : return a key with the lowest count, orgetMinKey() when no keys are stored.""
When several keys share the highest or lowest count, either getter may return any of them.
Example 1
Output: "c", "a"
The Idea
Picture a tally sheet at a vote count. Each time a name is read out, its tally goes up by one, and now and then a vote is struck off and the tally goes down. At any moment someone may ask who is in the lead, or who is last. This class is that tally sheet, with strings as the names.
In Example 1, a is counted once, b twice and c three times, so getMaxKey()getMinKey()HashMap{a=1, b=2, c=3}
So how can the highest and lowest counts be ready at every moment, without sorting all the keys again after each call? Notice how small each change is. The last inc("c")
That suggests grouping the keys by count. Put all keys with the same count in one bucket, and line the buckets up from the lowest count to the highest. Each bucket keeps a link to the bucket before it, called prevnext
Bucket 1 holds the keys with count 1, here {a}{b}{c}inc("c")
The dashed boxes, head and tail, are fixed end markers that hold no keys. A marker like this, which is always there and is never a real entry, is called a sentinel. Now the answers sit at the two ends: getMinKey()getMaxKey()
One piece is missing. To move c, the class must first know which bucket c is in. The map at the bottom of the picture, labelled where, sends each key straight to its bucket, so no call ever walks along the list.
Solution Approach
Four details remain to settle: what to do when the neighbouring count has no bucket, how keys arrive and leave, what happens to a bucket that runs empty, and why the list has sentinels at both ends.
Moving a key to the next count
What if the bucket for the next count does not exist yet, like bucket 3 before the last inc("c")
A dec
Keys that arrive and keys that reach 0
Where does a key come from on its first inc
At the other end, a decwhere
Removing empty buckets
What happens to a bucket when its last key leaves? Take the picture and call dec("b")inc("a")getMinKey()
Sentinels at both ends
Why keep head and tail at all? Without them, the first bucket would have no prevnext""
Java Solution
The class has these parts:
: one count, the setBucket of all keys with that count, and the linkskeys andprev .next andhead : the two sentinels, both with count 0. The constructor links head straight to tail.tail : the map from each key to its bucket. A key that is not in it counts as sitting inwhere .head : creates a bucket with a given count and links it in right after a given bucket.insertAfter : takes a key out of a bucket's set and unlinks the bucket if the set is now empty.removeKey andinc : find the key's bucket indec , put the key into the neighbouring bucket (creating it withwhere when its count is missing), then callinsertAfter on the old one. AremoveKey that takes a key to 0 only removes it, and adec on a key that was never added does nothing.dec andgetMaxKey : return any key fromgetMinKey ortail.prev , orhead.next when head links straight to tail."" andbuckets : print the list from head to tail as count:{keys}, followed by both getters. They exist only for the output.show
The maindec
import java.util.*;
public class AllOOneDataStructure {
// Buckets in a doubly linked list, sorted by count. Each holds all keys with that count.
private static class Bucket {
int count;
Set<String> keys = new HashSet<>();
Bucket prev, next;
Bucket(int count) { this.count = count; }
}
private final Bucket head = new Bucket(0), tail = new Bucket(0); // sentinels
private final Map<String, Bucket> where = new HashMap<>(); // key -> its bucket
public AllOOneDataStructure() {
head.next = tail;
tail.prev = head;
}
public void inc(String key) {
Bucket cur = where.getOrDefault(key, head); // a new key starts "at count 0"
Bucket next = cur.next;
if (next.count != cur.count + 1) next = insertAfter(cur, cur.count + 1);
next.keys.add(key);
where.put(key, next);
if (cur != head) removeKey(cur, key);
}
public void dec(String key) {
Bucket cur = where.get(key);
if (cur == null) return; // unknown key: nothing to do
if (cur.count == 1) {
where.remove(key); // count would reach 0: the key disappears
} else {
Bucket prev = cur.prev;
if (prev.count != cur.count - 1) prev = insertAfter(cur.prev, cur.count - 1);
prev.keys.add(key);
where.put(key, prev);
}
removeKey(cur, key);
}
public String getMaxKey() {
return tail.prev == head ? "" : tail.prev.keys.iterator().next();
}
public String getMinKey() {
return head.next == tail ? "" : head.next.keys.iterator().next();
}
private Bucket insertAfter(Bucket b, int count) {
Bucket nb = new Bucket(count);
nb.prev = b;
nb.next = b.next;
b.next.prev = nb;
b.next = nb;
return nb;
}
private void removeKey(Bucket b, String key) {
b.keys.remove(key);
if (b.keys.isEmpty()) { // unlink empty buckets
b.prev.next = b.next;
b.next.prev = b.prev;
}
}
// The bucket list from head to tail, as count:{keys}, for printing.
String buckets() {
StringJoiner sj = new StringJoiner(" ");
for (Bucket b = head.next; b != tail; b = b.next) {
sj.add(b.count + ":" + new TreeSet<>(b.keys).toString().replace('[', '{')
.replace(']', '}'));
}
return sj.length() == 0 ? "(empty)" : sj.toString();
}
void show(String call) {
System.out.printf("%-10s %-22s max \"%s\", min \"%s\"%n",
call, buckets(), getMaxKey(), getMinKey());
}
public static void main(String[] args) {
AllOOneDataStructure s = new AllOOneDataStructure();
for (String key : new String[] {"a", "b", "b", "c", "c", "c"}) s.inc(key);
s.show("Example 1");
s.dec("b");
s.show("dec(b)");
s.dec("c");
s.show("dec(c)");
s.dec("a");
s.show("dec(a)");
s.dec("x"); // never added
s.show("dec(x)");
s.dec("b");
s.dec("c");
s.dec("c");
s.show("dec b,c,c");
}
}
Running it prints:
Example 1 1:{a} 2:{b} 3:{c} max "c", min "a"
dec(b) 1:{a, b} 3:{c} max "c", min "a"
dec(c) 1:{a, b} 2:{c} max "c", min "a"
dec(a) 1:{b} 2:{c} max "c", min "b"
dec(x) 1:{b} 2:{c} max "c", min "b"
dec b,c,c (empty) max "", min ""
The Example 1 line matches the picture, 1:{a} 2:{b} 3:{c}dec(b)1:{a, b}3:{c}getMinKey()
The dec(c)dec(a)dec(x)""
The unlinking in removeKeyiffalseinc("a")getMaxKey()getMinKey()NoSuchElementException
Complexity
Every call touches one key, a few buckets next to each other and a handful of links, however many keys are stored.
- Time: O(1) on average per operation, because
andinc do one lookup indec , move the key to a neighbouring bucket and insert or unlink at most one bucket each, and the getters read an end of the list. "On average" comes fromwhere andHashMap , whose lookups take one step unless many keys share a hash slot.HashSet - Space: O(k) for k distinct keys, because
has one entry per key, each key sits in one bucket's set, and with empty buckets unlinked there are never more buckets than keys.where
The same list of count buckets is at the heart of