15% off all plans & roadmaps Use code

See plans

All O`one Data Structure

Updated

TL;DR: Build a counter that returns a key with the smallest or largest count in O(1) per call. Keep a doubly linked list of count buckets, each holding its keys, plus a hash map from each key to its bucket.

Problem

Design a data structure that stores the count of each string. It must return a string with the minimum count and a string with the maximum count.

Implement the AllOne class:

  • AllOne() initializes the object.
  • inc(String key) increments the count of key by 1. If key is not in the structure, it is inserted with count 1.
  • dec(String key) decrements the count of key by 1. If the count becomes 0, remove key. The key is guaranteed to exist before the call.
  • getMaxKey() returns one of the keys with the maximum count. It returns "" if the structure is empty.
  • getMinKey() returns one of the keys with the minimum count. It returns "" if the structure is empty.

Each function must run in O(1) average time.

Example 1

Input: ["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"]
[[], ["hello"], ["hello"], [], [], ["leet"], [], []]
Output: [null, null, null, "hello", "hello", null, "hello", "leet"]
Explanation: inc("hello") runs twice, so "hello" has count 2. Both getMaxKey and getMinKey return "hello". Then inc("leet") adds "leet" with count 1. getMaxKey still returns "hello", and getMinKey returns "leet".

Constraints

  • 1 <= key.length <= 10
  • key consists of lowercase English letters.
  • For each call to dec, key exists in the data structure.
  • At most 5 * 10^4 calls are made to inc, dec, getMaxKey, and getMinKey.

Constraints that matter

  • At most 5 * 10^4 calls with O(1) average per call rules out scanning all keys inside getMaxKey or getMinKey. Up to 25,000 max queries over 25,000 keys would mean about 6.25 * 10^8 steps.
  • inc and dec change a count by exactly 1. A key can only move to a neighbouring count level, so its new position is one step away from its old one.
  • Keys have length at most 10 and use lowercase letters. Hashing a key costs a constant amount, so hash map operations stay O(1).
  • Counts can reach 5 * 10^4 for a single key, so the counts need no special handling beyond a normal integer.

View on LeetCode

Hints

Hint 1

The hard part is the two extreme queries.

Hint 2

Store each key's count in a hash map.

Solution

Intuition

The hard part is the two extreme queries. A hash map gives each key's count in O(1), but finding the largest or smallest count needs a full scan. The problem asks for both extremes after any sequence of changes, so the structure must keep them ready at all times.

Picture a row of labeled boxes sorted by count, with each key's name filed in one box. The hash map is an index card that says which box each name is in, so moving a name to the next box takes one step.

Two facts point to the fix. Keys with the same count are interchangeable for getMaxKey and getMinKey, so you can group keys by count. Also, each inc or dec changes one count by exactly 1, so a key only moves to a neighbouring count level.

This pattern combines two standard structures so that each covers the other's weakness. The hash map gives direct lookup. The doubly linked list of frequency buckets gives ordering.

A doubly linked list removes a node in O(1) when you already hold a pointer to it. The hash map supplies that pointer for each key. Sentinel head and tail nodes with count 0 make the empty case and the end cases disappear from the code.

Watch the pattern animation

Worked example

Input: AllOne(), inc("a"), inc("b"), inc("a"), dec("a"), getMaxKey(), getMinKey()
Output: null, null, null, null, null, "a", "a"
Explanation: After the first three increments, "a" has count 2 and "b" has count 1. The decrement drops "a" back to count 1, so both keys now have count 1. Both keys tie for the maximum and the minimum, so either one is a valid answer. The trace below returns "a", which matches the expected output.

Approach 1: Brute force with a hash map and full scan

Store each key's count in a hash map. inc and dec change one entry directly. getMaxKey and getMinKey scan every entry to find the largest or smallest count.

What is slow: the two extreme queries repeat a full pass over all keys, even though only one count changed since the last query. With many distinct keys and many queries, that pass dominates the running time.

Steps

  1. Create a hash map from each key to its integer count.
  2. For inc, add 1 to the key's count, starting from 0 when the key is absent.
  3. For dec, subtract 1 from the count, and delete the key when the count reaches 0.
  4. For getMaxKey, return "" if the map is empty. Otherwise scan every entry and keep the key with the largest count.
  5. For getMinKey, use the same scan and keep the key with the smallest count.

Dry run

Start with an empty map {}.

  • inc("a") gives {a: 1}.
  • inc("b") gives {a: 1, b: 1}.
  • inc("a") gives {a: 2, b: 1}.
  • dec("a") gives {a: 1, b: 1}.
  • getMaxKey() scans both entries. Both counts are 1, so either key is valid. The trace reports "a", which matches the expected output.
  • getMinKey() scans the same two entries and reports "a" as well.

Complexity

Timeinc and dec: O(1) average. getMaxKey and getMinKey: O(n).
SpaceO(n)

Let n be the number of distinct live keys. inc and dec do a fixed number of hash map operations, so each is O(1) average. getMaxKey and getMinKey loop over all n entries once, so each is O(n). The map holds one entry per live key, so the space is O(n).

PythonTested in our runner

class AllOne:
    def __init__(self):
        self.counts = {}

    def inc(self, key: str) -> None:
        self.counts[key] = self.counts.get(key, 0) + 1

    def dec(self, key: str) -> None:
        self.counts[key] -= 1
        if self.counts[key] == 0:
            del self.counts[key]

    def getMaxKey(self) -> str:
        if not self.counts:
            return ''
        return max(self.counts, key=self.counts.get)

    def getMinKey(self) -> str:
        if not self.counts:
            return ''
        return min(self.counts, key=self.counts.get)

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 2: Sorted bucket list with a hash mapOptimalDesign (General/Specific)

Group keys into buckets, one bucket per count value. Each bucket holds a set of keys. Link the buckets in a doubly linked list sorted by count, with the smallest count at the front. The first real bucket holds the minimum and the last real bucket holds the maximum.

What is slow: the brute force scan rebuilds the answer from scratch on every query. The insight that fixes it: inc and dec move a key by exactly one count level, so its new bucket sits right next to its old bucket.

You can link or unlink that neighbour in O(1) once you hold the old bucket's node. A hash map from each key to its bucket gives that node directly.

Why it is correct. The list always stays sorted by count with no empty real buckets, and every key sits in the bucket matching its count. Since each change moves a key exactly one count level, it lands in an adjacent bucket, so sorting is preserved. The first and last real buckets therefore hold the smallest and largest counts, so reading them gives the true answers.

Steps

  1. Create sentinel nodes head (count 0) and tail, and link them to each other. Real buckets go between them.
  2. Keep where, a hash map from each live key to the bucket that holds it.
  3. For inc, take the key's current bucket, or head if the key is new. The target count is that bucket's count plus 1, or 1 for a new key.
  4. If the bucket after the current one does not have the target count, insert a new bucket after the current one. Move the key into the target bucket and update where.
  5. Remove the key from its old bucket. If the old bucket is no longer head and is now empty, unlink it.
  6. For dec, the target count is the key's count minus 1. If the target is 0, delete the key from where. Otherwise reuse the previous bucket when its count matches, or insert a new bucket before the current one.
  7. Move the key into the target bucket, remove it from its old bucket, and unlink the old bucket if it is empty.
  8. getMaxKey returns "" when tail.prev is head, and otherwise returns any key from tail.prev. getMinKey does the same with head.next.

Dry run

Each row shows the state after one call. Buckets appear in list order from head to tail, written as count:{keys}. B1 and B2 name the bucket nodes.

StepCallBuckets (list order)where (key to bucket)
0starthead <-> tail{}
1inc("a")B1 = 1:{a} (new, inserted after head)a to B1
2inc("b")B1 = 1:{a, b} (head.next already has count 1, so reuse it)a to B1, b to B1
3inc("a")B1 = 1:{b}, B2 = 2:{a} (B1.next is tail, so insert B2 after B1)a to B2, b to B1
4dec("a")B1 = 1:{a, b} (B2.prev is B1 with count 1, so a joins B1). B2 is empty and gets unlinkeda to B1, b to B1
5getMaxKey()tail.prev is B1, which is not head, so return a key from {a, b}: "a"unchanged
6getMinKey()head.next is B1, so return a key from {a, b}: "a"unchanged

At step 4, both a and b share bucket B1, so the max and min buckets are the same node. The result "a" matches the expected output.

Complexity

TimeO(1) average per operation
SpaceO(n)

Let n be the number of distinct live keys. Each inc or dec does a fixed number of hash map lookups, inserts and deletes, each O(1) average. It also does at most one node insert and one node unlink, each O(1) because the neighbour is known. getMaxKey and getMinKey read one sentinel neighbour and take one key from a set, which is O(1) average. Every real bucket is non-empty, so there are at most n buckets and the structure stores O(n) entries.

PythonTested in our runner

class Bucket:
    __slots__ = ("count", "keys", "prev", "next")

    def __init__(self, count):
        self.count = count
        self.keys = set()
        self.prev = None
        self.next = None


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

    def _insert_after(self, node, count):
        new = Bucket(count)
        new.prev = node
        new.next = node.next
        node.next.prev = new
        node.next = new
        return new

    def _remove(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev

    def inc(self, key: str) -> None:
        if key in self.where:
            cur = self.where[key]
            target = cur.count + 1
        else:
            cur = self.head
            target = 1
        nxt = cur.next
        if nxt is self.tail or nxt.count != target:
            nxt = self._insert_after(cur, target)
        nxt.keys.add(key)
        self.where[key] = nxt
        if cur is not self.head:
            cur.keys.discard(key)
            if not cur.keys:
                self._remove(cur)

    def dec(self, key: str) -> None:
        cur = self.where[key]
        target = cur.count - 1
        if target == 0:
            del self.where[key]
        else:
            prev = cur.prev
            if prev is self.head or prev.count != target:
                prev = self._insert_after(prev, target)
            prev.keys.add(key)
            self.where[key] = prev
        cur.keys.discard(key)
        if not cur.keys:
            self._remove(cur)

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

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

Common mistakes

  • Unlinking the old bucket before the target bucket is linked. In inc, if cur is unlinked first, nxt may point at a detached node. Link or find the target first, add the key, and only then unlink the old bucket.
  • Inserting the new count level after cur.prev in inc. That places count 2 before count 1 and breaks the sorted order. inc inserts after the current bucket, and dec inserts after the previous bucket, which is before the current one.
  • Creating a bucket for count 0 in dec. When the count reaches 0, delete the key from the map and skip the list insert. A count 0 bucket would make getMinKey return a key that is no longer stored.
  • Leaving an empty bucket in the list. Then getMaxKey or getMinKey can read a bucket with no keys. Unlink a bucket as soon as its key set becomes empty, unless it is a sentinel.
  • Reading tail.prev.keys without checking the sentinel first. An empty structure has only head and tail, so getMaxKey must test tail.prev == head and return "" before it reads any keys.

Edge cases

  • Empty structure: getMaxKey and getMinKey both return "".
  • One key incremented then decremented: the structure empties, the sentinels link to each other again, and both getters return "".
  • Two keys with the same count: both sit in one bucket, so getMaxKey and getMinKey return one of them.
  • dec on a key with count 2 when no count 1 bucket exists: a new count 1 bucket goes right after head, and the key moves into it.
  • One key incremented many times, up to 5 * 10^4: the list never holds more than one real bucket at a time, because the key always leaves its old bucket.

Follow-ups interviewers ask

What if a single call can change a count by more than 1?
The neighbour trick breaks. You would need to search for the right position, which costs O(number of buckets) when you walk the list. A balanced tree or a sorted map finds that position in O(log n), so each call becomes O(log n) instead of O(1).
How would you return every key that has the maximum count?
Return the key set of the last real bucket. It holds exactly the keys with the maximum count, since every other bucket has a smaller count. Copying those k keys into a list takes O(k) time.
Could a pair of heaps replace the bucket list?
A max-heap and a min-heap with lazy deletion can answer both queries. Each count change then costs O(log n), so the O(1) bound is lost. The bucket list works here because each change moves a key by exactly one level.

All O`one Data Structure FAQ

What is the time complexity of All O`one Data Structure?

Each of the four methods runs in O(1) average time. inc and dec do a fixed number of hash map and linked list operations, and the getters read a sentinel neighbour. Space is O(n) in the number of distinct keys.

Why use a hash map with a doubly linked list for All O`one?

The hash map finds a key's bucket in O(1). The doubly linked list keeps the count levels sorted, so the minimum and maximum sit at its ends. Together they meet the O(1) bound for every call.

Can All O`one Data Structure be solved in O(1) extra space?

No. The structure must remember every distinct key and its count, so its size grows with the number of keys. The bucket list adds at most one node per distinct count, which still stays within O(n).

Why does each count change by exactly 1 matter?

It means a key only moves to the neighbouring count level. Without this, finding the new position would need a search through the list, and the O(1) bound would fail.

Why does getMaxKey return any key with the maximum count?

The problem accepts any key with the maximal count. The last real bucket holds all such keys, so returning one of them is correct.

Asked at

See which companies ask this — Pro

Practise it