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:

When several keys share the highest or lowest count, either getter may return any of them.

Example 1
Input: inc("a"), inc("b"), inc("b"), inc("c"), inc("c"), inc("c"), getMaxKey(), getMinKey()
Output: "c", "a"
Solution

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() answers c and getMinKey() answers a. Keeping the counts is easy: a HashMap from key to count, here {a=1, b=2, c=3}, updates a count in one step. But the map has no idea which count is the largest. Finding c means looking at every key, and with a million keys that is a million looks for each question.

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") took c from 2 to 3, not from 2 to 7. A key only ever steps to the count right above or right below its own.

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 prev, and to the one after it, called next. A chain of buckets linked both ways like this is a doubly linked list. Here is the list after the six calls of Example 1:

The bucket list after Example 1: head, bucket 1 with a, bucket 2 with b, bucket 3 with c, tail, linked by next and prev arrows. getMinKey reads head.next and getMaxKey reads tail.prev. The last inc(c) moved c from bucket 2 to a new bucket 3. The map where sends a to bucket 1, b to bucket 2 and c to bucket 3.

Bucket 1 holds the keys with count 1, here {a}. Bucket 2 holds {b} and bucket 3 holds {c}. Follow the orange arrow: the last inc("c") moved c out of bucket 2 into bucket 3, which did not exist yet, so it was created right after bucket 2.

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() reads the bucket right after head, and getMaxKey() reads the bucket right before tail.

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")? The list is sorted and no two buckets share a count, so the bucket after the current one has either the next count or a higher one. If its count is not one more, a new bucket with that count goes in right between the two, and the list stays sorted without any search.

A dec works the same way in the other direction. It looks at the bucket before the current one, and creates a bucket for the count one lower in between when the counts do not fit.

Keys that arrive and keys that reach 0

Where does a key come from on its first inc? The code treats it as sitting in head, whose count is 0. Then a new key moves to count 1 exactly like any other key moves up, and bucket 1 is created if it is missing.

At the other end, a dec on a key with count 1 does not move the key into a bucket for count 0. It removes the key from its bucket and from where, and the key is gone.

Removing empty buckets

What happens to a bucket when its last key leaves? Take the picture and call dec("b"): b drops to bucket 1, and bucket 2 is left with no keys. If it stayed, it would sit between buckets 1 and 3 holding nothing. An empty bucket can also end up right after head. Call inc("a") twice on a new object, and bucket 1 is left empty while a sits in bucket 2, so getMinKey() would find no key to return. So an empty bucket is unlinked at once: the buckets on either side are linked to each other, skipping it. Then the buckets at both ends always hold real keys.

Sentinels at both ends

Why keep head and tail at all? Without them, the first bucket would have no prev and the last no next, and every insert and unlink would need extra checks for the ends. With them, every real bucket has a neighbour on both sides, and linking or unlinking is the same four link updates everywhere. An empty structure is simply head linked straight to tail, which is how the getters know to return "".

Java Solution

The class has these parts:

  • Bucket: one count, the set keys of all keys with that count, and the links prev and next.
  • head and tail: the two sentinels, both with count 0. The constructor links head straight to tail.
  • where: the map from each key to its bucket. A key that is not in it counts as sitting in head.
  • insertAfter: creates a bucket with a given count and links it in right after a given bucket.
  • removeKey: takes a key out of a bucket's set and unlinks the bucket if the set is now empty.
  • inc and dec: find the key's bucket in where, put the key into the neighbouring bucket (creating it with insertAfter when its count is missing), then call removeKey on the old one. A dec that takes a key to 0 only removes it, and a dec on a key that was never added does nothing.
  • getMaxKey and getMinKey: return any key from tail.prev or head.next, or "" when head links straight to tail.
  • buckets and show: print the list from head to tail as count:{keys}, followed by both getters. They exist only for the output.

The main method runs the six calls of Example 1. Then a series of dec calls empties a bucket, recreates a missing one, removes a key, tries a key that was never added, and empties the whole structure.

Java
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:

Output
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}, and gives max "c" and min "a". On the dec(b) line, b has joined a in bucket 1, and there is no 2 between 1:{a, b} and 3:{c}: the empty bucket was unlinked. Bucket 1 now holds two keys and getMinKey() returned a, though b would be just as correct.

The dec(c) line shows the missing count being filled in. Key c needed count 2, so a new bucket 2 was created between buckets 1 and 3. After dec(a), a reached 0 and left, and min turned to "b". The dec(x) line is unchanged, and the last line shows the empty structure answering "" to both getters.

The unlinking in removeKey is easy to leave out. With its if check replaced by false, calling inc("a") twice leaves an empty bucket 1 right after head. The call getMaxKey() still returns a, but getMinKey() throws NoSuchElementException, because it asks an empty set for a key.

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 inc and dec do one lookup in where, 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 from HashMap and HashSet, whose lookups take one step unless many keys share a hash slot.
  • Space: O(k) for k distinct keys, because where 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.

The same list of count buckets is at the heart of LFU Cache, which uses it to find the least used entry.