15% off all plans & roadmaps Use code
See plansAll O`one Data Structure
- LeetCode 432
- Hard
- Design Patterns
- Design (General/Specific)
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 ofkeyby 1. Ifkeyis not in the structure, it is inserted with count 1.dec(String key)decrements the count ofkeyby 1. If the count becomes 0, removekey. 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 <= 10keyconsists of lowercase English letters.- For each call to
dec,keyexists in the data structure. - At most
5 * 10^4calls are made toinc,dec,getMaxKey, andgetMinKey.
Constraints that matter
- At most 5 * 10^4 calls with O(1) average per call rules out scanning all keys inside
getMaxKeyorgetMinKey. Up to 25,000 max queries over 25,000 keys would mean about 6.25 * 10^8 steps. incanddecchange 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.
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.
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
- Create a hash map from each key to its integer count.
- For
inc, add 1 to the key's count, starting from 0 when the key is absent. - For
dec, subtract 1 from the count, and delete the key when the count reaches 0. - For
getMaxKey, return "" if the map is empty. Otherwise scan every entry and keep the key with the largest count. - 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
| Time | inc and dec: O(1) average. getMaxKey and getMinKey: O(n). |
|---|---|
| Space | O(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)JavaTested in our runner
import java.util.*;
class AllOne {
private Map<String, Integer> counts = new HashMap<>();
public AllOne() {
}
public void inc(String key) {
counts.put(key, counts.getOrDefault(key, 0) + 1);
}
public void dec(String key) {
int c = counts.get(key) - 1;
if (c == 0) {
counts.remove(key);
} else {
counts.put(key, c);
}
}
public String getMaxKey() {
if (counts.isEmpty()) return "";
Map.Entry<String, Integer> top = null;
for (Map.Entry<String, Integer> e : counts.entrySet()) {
if (top == null || e.getValue() > top.getValue()) top = e;
}
return top.getKey();
}
public String getMinKey() {
if (counts.isEmpty()) return "";
Map.Entry<String, Integer> low = null;
for (Map.Entry<String, Integer> e : counts.entrySet()) {
if (low == null || e.getValue() < low.getValue()) low = e;
}
return low.getKey();
}
}C++Tested in our runner
using namespace std;
class AllOne {
unordered_map<string, int> counts;
public:
AllOne() {}
void inc(string key) {
counts[key]++;
}
void dec(string key) {
if (--counts[key] == 0) counts.erase(key);
}
string getMaxKey() {
if (counts.empty()) return "";
auto best = counts.begin();
for (auto it = counts.begin(); it != counts.end(); ++it)
if (it->second > best->second) best = it;
return best->first;
}
string getMinKey() {
if (counts.empty()) return "";
auto best = counts.begin();
for (auto it = counts.begin(); it != counts.end(); ++it)
if (it->second < best->second) best = it;
return best->first;
}
};JavaScriptTested in our runner
var AllOne = function() {
this.counts = new Map();
};
AllOne.prototype.inc = function(key) {
this.counts.set(key, (this.counts.get(key) || 0) + 1);
};
AllOne.prototype.dec = function(key) {
const c = this.counts.get(key) - 1;
if (c === 0) {
this.counts.delete(key);
} else {
this.counts.set(key, c);
}
};
AllOne.prototype.getMaxKey = function() {
if (this.counts.size === 0) return "";
let best = null;
let bestCount = -1;
for (const [k, v] of this.counts) {
if (v > bestCount) {
best = k;
bestCount = v;
}
}
return best;
};
AllOne.prototype.getMinKey = function() {
if (this.counts.size === 0) return "";
let best = null;
let bestCount = Infinity;
for (const [k, v] of this.counts) {
if (v < bestCount) {
best = k;
bestCount = v;
}
}
return best;
};GoTested in our runner
type AllOne struct {
counts map[string]int
}
func Constructor() AllOne {
return AllOne{counts: map[string]int{}}
}
func (this *AllOne) inc(key string) {
this.counts[key]++
}
func (this *AllOne) dec(key string) {
this.counts[key]--
if this.counts[key] == 0 {
delete(this.counts, key)
}
}
func (this *AllOne) getMaxKey() string {
best, bestCount := "", 0
for k, v := range this.counts {
if best == "" || v > bestCount {
best, bestCount = k, v
}
}
return best
}
func (this *AllOne) getMinKey() string {
best, bestCount := "", 0
for k, v := range this.counts {
if best == "" || v < bestCount {
best, bestCount = k, v
}
}
return best
}C#Tested in our runner
public class AllOne {
private Dictionary<string, int> counts = new Dictionary<string, int>();
public AllOne() {
}
public void inc(string key) {
counts[key] = counts.ContainsKey(key) ? counts[key] + 1 : 1;
}
public void dec(string key) {
counts[key]--;
if (counts[key] == 0) counts.Remove(key);
}
public string getMaxKey() {
if (counts.Count == 0) return "";
var best = counts.First();
foreach (var kv in counts) if (kv.Value > best.Value) best = kv;
return best.Key;
}
public string getMinKey() {
if (counts.Count == 0) return "";
var best = counts.First();
foreach (var kv in counts) if (kv.Value < best.Value) best = kv;
return best.Key;
}
}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 infographicSolution 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
- Create sentinel nodes
head(count 0) andtail, and link them to each other. Real buckets go between them. - Keep
where, a hash map from each live key to the bucket that holds it. - For
inc, take the key's current bucket, orheadif the key is new. The target count is that bucket's count plus 1, or 1 for a new key. - 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. - Remove the key from its old bucket. If the old bucket is no longer
headand is now empty, unlink it. - For
dec, the target count is the key's count minus 1. If the target is 0, delete the key fromwhere. Otherwise reuse the previous bucket when its count matches, or insert a new bucket before the current one. - Move the key into the target bucket, remove it from its old bucket, and unlink the old bucket if it is empty.
getMaxKeyreturns "" whentail.previshead, and otherwise returns any key fromtail.prev.getMinKeydoes the same withhead.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.
| Step | Call | Buckets (list order) | where (key to bucket) |
|---|---|---|---|
| 0 | start | head <-> tail | {} |
| 1 | inc("a") | B1 = 1:{a} (new, inserted after head) | a to B1 |
| 2 | inc("b") | B1 = 1:{a, b} (head.next already has count 1, so reuse it) | a to B1, b to B1 |
| 3 | inc("a") | B1 = 1:{b}, B2 = 2:{a} (B1.next is tail, so insert B2 after B1) | a to B2, b to B1 |
| 4 | dec("a") | B1 = 1:{a, b} (B2.prev is B1 with count 1, so a joins B1). B2 is empty and gets unlinked | a to B1, b to B1 |
| 5 | getMaxKey() | tail.prev is B1, which is not head, so return a key from {a, b}: "a" | unchanged |
| 6 | getMinKey() | 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
| Time | O(1) average per operation |
|---|---|
| Space | O(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))JavaTested in our runner
import java.util.*;
class AllOne {
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);
private final Bucket tail = new Bucket(0);
private final Map<String, Bucket> where = new HashMap<>();
public AllOne() {
head.next = tail;
tail.prev = head;
}
private Bucket insertAfter(Bucket node, int count) {
Bucket b = new Bucket(count);
b.prev = node;
b.next = node.next;
node.next.prev = b;
node.next = b;
return b;
}
private void unlink(Bucket node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
public void inc(String key) {
Bucket cur = head;
int target = 1;
if (where.containsKey(key)) {
cur = where.get(key);
target = cur.count + 1;
}
Bucket nxt = cur.next;
if (nxt == tail || nxt.count != target) {
nxt = insertAfter(cur, target);
}
nxt.keys.add(key);
where.put(key, nxt);
if (cur != head) {
cur.keys.remove(key);
if (cur.keys.isEmpty()) unlink(cur);
}
}
public void dec(String key) {
Bucket cur = where.get(key);
int target = cur.count - 1;
if (target == 0) {
where.remove(key);
} else {
Bucket prev = cur.prev;
if (prev == head || prev.count != target) {
prev = insertAfter(prev, target);
}
prev.keys.add(key);
where.put(key, prev);
}
cur.keys.remove(key);
if (cur.keys.isEmpty()) unlink(cur);
}
public String getMaxKey() {
if (tail.prev == head) return "";
return tail.prev.keys.iterator().next();
}
public String getMinKey() {
if (head.next == tail) return "";
return head.next.keys.iterator().next();
}
}C++Tested in our runner
using namespace std;
class AllOne {
struct Bucket {
int count;
unordered_set<string> keys;
Bucket* prev;
Bucket* next;
explicit Bucket(int c) : count(c), prev(nullptr), next(nullptr) {}
};
Bucket* head;
Bucket* tail;
unordered_map<string, Bucket*> where;
Bucket* insertAfter(Bucket* node, int count) {
Bucket* b = new Bucket(count);
b->prev = node;
b->next = node->next;
node->next->prev = b;
node->next = b;
return b;
}
void unlinkBucket(Bucket* node) {
node->prev->next = node->next;
node->next->prev = node->prev;
delete node;
}
public:
AllOne() {
head = new Bucket(0);
tail = new Bucket(0);
head->next = tail;
tail->prev = head;
}
~AllOne() {
while (head) {
Bucket* nx = head->next;
delete head;
head = nx;
}
}
void inc(string key) {
Bucket* cur = head;
int target = 1;
auto it = where.find(key);
if (it != where.end()) {
cur = it->second;
target = cur->count + 1;
}
Bucket* nxt = cur->next;
if (nxt == tail || nxt->count != target) {
nxt = insertAfter(cur, target);
}
nxt->keys.insert(key);
where[key] = nxt;
if (cur != head) {
cur->keys.erase(key);
if (cur->keys.empty()) unlinkBucket(cur);
}
}
void dec(string key) {
Bucket* cur = where[key];
int target = cur->count - 1;
if (target == 0) {
where.erase(key);
} else {
Bucket* prev = cur->prev;
if (prev == head || prev->count != target) {
prev = insertAfter(prev, target);
}
prev->keys.insert(key);
where[key] = prev;
}
cur->keys.erase(key);
if (cur->keys.empty()) unlinkBucket(cur);
}
string getMaxKey() {
if (tail->prev == head) return "";
return *tail->prev->keys.begin();
}
string getMinKey() {
if (head->next == tail) return "";
return *head->next->keys.begin();
}
};JavaScriptTested in our runner
var AllOne = function() {
this.head = { count: 0, keys: new Set(), prev: null, next: null };
this.tail = { count: 0, keys: new Set(), prev: null, next: null };
this.head.next = this.tail;
this.tail.prev = this.head;
this.where = new Map();
};
AllOne.prototype._insertAfter = function(node, count) {
const b = { count: count, keys: new Set(), prev: node, next: node.next };
node.next.prev = b;
node.next = b;
return b;
};
AllOne.prototype._unlink = function(node) {
node.prev.next = node.next;
node.next.prev = node.prev;
};
AllOne.prototype.inc = function(key) {
let cur = this.head;
let target = 1;
if (this.where.has(key)) {
cur = this.where.get(key);
target = cur.count + 1;
}
let nxt = cur.next;
if (nxt === this.tail || nxt.count !== target) {
nxt = this._insertAfter(cur, target);
}
nxt.keys.add(key);
this.where.set(key, nxt);
if (cur !== this.head) {
cur.keys.delete(key);
if (cur.keys.size === 0) this._unlink(cur);
}
};
AllOne.prototype.dec = function(key) {
const cur = this.where.get(key);
const target = cur.count - 1;
if (target === 0) {
this.where.delete(key);
} else {
let prev = cur.prev;
if (prev === this.head || prev.count !== target) {
prev = this._insertAfter(prev, target);
}
prev.keys.add(key);
this.where.set(key, prev);
}
cur.keys.delete(key);
if (cur.keys.size === 0) this._unlink(cur);
};
AllOne.prototype.getMaxKey = function() {
if (this.tail.prev === this.head) return "";
return this.tail.prev.keys.values().next().value;
};
AllOne.prototype.getMinKey = function() {
if (this.head.next === this.tail) return "";
return this.head.next.keys.values().next().value;
};GoTested in our runner
type bucket struct {
count int
keys map[string]bool
prev *bucket
next *bucket
}
type AllOne struct {
head *bucket
tail *bucket
where map[string]*bucket
}
func Constructor() AllOne {
head := &bucket{count: 0, keys: map[string]bool{}}
tail := &bucket{count: 0, keys: map[string]bool{}}
head.next = tail
tail.prev = head
return AllOne{head: head, tail: tail, where: map[string]*bucket{}}
}
func insertAfter(node *bucket, count int) *bucket {
b := &bucket{count: count, keys: map[string]bool{}, prev: node, next: node.next}
node.next.prev = b
node.next = b
return b
}
func unlinkBucket(node *bucket) {
node.prev.next = node.next
node.next.prev = node.prev
}
func (this *AllOne) inc(key string) {
cur := this.head
target := 1
if c, ok := this.where[key]; ok {
cur = c
target = c.count + 1
}
nxt := cur.next
if nxt == this.tail || nxt.count != target {
nxt = insertAfter(cur, target)
}
nxt.keys[key] = true
this.where[key] = nxt
if cur != this.head {
delete(cur.keys, key)
if len(cur.keys) == 0 {
unlinkBucket(cur)
}
}
}
func (this *AllOne) dec(key string) {
cur := this.where[key]
target := cur.count - 1
if target == 0 {
delete(this.where, key)
} else {
prev := cur.prev
if prev == this.head || prev.count != target {
prev = insertAfter(prev, target)
}
prev.keys[key] = true
this.where[key] = prev
}
delete(cur.keys, key)
if len(cur.keys) == 0 {
unlinkBucket(cur)
}
}
func (this *AllOne) getMaxKey() string {
if this.tail.prev == this.head {
return ""
}
for k := range this.tail.prev.keys {
return k
}
return ""
}
func (this *AllOne) getMinKey() string {
if this.head.next == this.tail {
return ""
}
for k := range this.head.next.keys {
return k
}
return ""
}C#Tested in our runner
public class AllOne {
private class Bucket {
public int Count;
public HashSet<string> Keys = new HashSet<string>();
public Bucket Prev, Next;
public Bucket(int count) {
Count = count;
}
}
private Bucket head = new Bucket(0);
private Bucket tail = new Bucket(0);
private Dictionary<string, Bucket> keyBucket = new Dictionary<string, Bucket>();
public AllOne() {
head.Next = tail;
tail.Prev = head;
}
private Bucket InsertAfter(Bucket node, int count) {
Bucket b = new Bucket(count);
b.Prev = node;
b.Next = node.Next;
node.Next.Prev = b;
node.Next = b;
return b;
}
private void Unlink(Bucket node) {
node.Prev.Next = node.Next;
node.Next.Prev = node.Prev;
}
public void inc(string key) {
Bucket cur = head;
int target = 1;
if (keyBucket.ContainsKey(key)) {
cur = keyBucket[key];
target = cur.Count + 1;
}
Bucket nxt = cur.Next;
if (nxt == tail || nxt.Count != target) {
nxt = InsertAfter(cur, target);
}
nxt.Keys.Add(key);
keyBucket[key] = nxt;
if (cur != head) {
cur.Keys.Remove(key);
if (cur.Keys.Count == 0) Unlink(cur);
}
}
public void dec(string key) {
Bucket cur = keyBucket[key];
int target = cur.Count - 1;
if (target == 0) {
keyBucket.Remove(key);
} else {
Bucket prev = cur.Prev;
if (prev == head || prev.Count != target) {
prev = InsertAfter(prev, target);
}
prev.Keys.Add(key);
keyBucket[key] = prev;
}
cur.Keys.Remove(key);
if (cur.Keys.Count == 0) Unlink(cur);
}
public string getMaxKey() {
if (tail.Prev == head) return "";
return tail.Prev.Keys.First();
}
public string getMinKey() {
if (head.Next == tail) return "";
return head.Next.Keys.First();
}
}Common mistakes
- Unlinking the old bucket before the target bucket is linked. In
inc, ifcuris unlinked first,nxtmay 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.previninc. That places count 2 before count 1 and breaks the sorted order.incinserts after the current bucket, anddecinserts 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 makegetMinKeyreturn a key that is no longer stored. - Leaving an empty bucket in the list. Then
getMaxKeyorgetMinKeycan 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.keyswithout checking the sentinel first. An empty structure has onlyheadandtail, sogetMaxKeymust testtail.prev == headand return "" before it reads any keys.
Edge cases
- Empty structure:
getMaxKeyandgetMinKeyboth 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
getMaxKeyandgetMinKeyreturn one of them. decon a key with count 2 when no count 1 bucket exists: a new count 1 bucket goes right afterhead, 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
Related problems
- Find Median from Data Stream · same technique: Design (General/Specific)
- LFU Cache · same technique: Design (General/Specific)
- Design Search Autocomplete System · same technique: Design (General/Specific)
- Design a Text Editor · same technique: Design (General/Specific)
- Range Module · same technique: Design (General/Specific)
- Word Squares · same pattern: Design Patterns
- Prefix and Suffix Search · same pattern: Design Patterns
- LRU Cache · same pattern: Design Patterns
- Min Stack · same pattern: Design Patterns
- Time Based Key-Value Store · same pattern: Design Patterns