SDE & MLE Prep

432. All O`one Data Structure

Problem

Design AllOne, which stores string counts: inc(key) adds 1 (inserting the key with count 1 if new), dec(key) subtracts 1 (removing the key at 0; the key always exists), getMaxKey() and getMinKey() return a key with the highest or lowest count ("" if empty). Every operation must run in O(1) average time.

Example: inc("hello") ×2 → getMaxKey() = "hello"; inc("leet") → getMaxKey() = "hello", getMinKey() = "leet"

Like LFU: a doubly linked list of count buckets in increasing order, each holding a set of keys, plus key → bucket. inc/dec move a key to the neighbouring bucket (creating it if the count isn't there), deleting emptied buckets. Min/max = first/last bucket.

head <-> [1: {b}] <-> [2: {a, c}] <-> [5: {d}] <-> tail
getMinKey -> b      getMaxKey -> d      inc(c) -> c moves to new bucket [3]

Complexity: O(1) per operation.

class Bucket:
    def __init__(self, cnt):
        self.cnt, self.keys, self.prev, self.next = cnt, set(), None, None

class AllOne:
    def __init__(self):
        self.head, self.tail = Bucket(0), Bucket(0)
        self.head.next, self.tail.prev = self.tail, self.head
        self.where = {}

    def _after(self, node, cnt):
        b = Bucket(cnt)
        b.prev, b.next = node, node.next
        node.next.prev = b
        node.next = b
        return b

    def _drop_if_empty(self, b):
        if not b.keys:
            b.prev.next, b.next.prev = b.next, b.prev

    def inc(self, key: str) -> None:
        cur = self.where.get(key, self.head)
        nxt = cur.next
        if nxt is self.tail or nxt.cnt != cur.cnt + 1:
            nxt = self._after(cur, cur.cnt + 1)
        nxt.keys.add(key)
        self.where[key] = nxt
        if cur is not self.head:
            cur.keys.discard(key)
            self._drop_if_empty(cur)

    def dec(self, key: str) -> None:
        cur = self.where[key]
        if cur.cnt == 1:
            del self.where[key]
        else:
            prv = cur.prev
            if prv is self.head or prv.cnt != cur.cnt - 1:
                prv = self._after(cur.prev, cur.cnt - 1)
            prv.keys.add(key)
            self.where[key] = prv
        cur.keys.discard(key)
        self._drop_if_empty(cur)

    def getMaxKey(self) -> str:
        return next(iter(self.tail.prev.keys)) if self.tail.prev is not self.head else ""

    def getMinKey(self) -> str:
        return next(iter(self.head.next.keys)) if self.head.next is not self.tail else ""