All O(1) Data Structure
Design a data structure supporting four operations, each in O(1) average time: inc(key) increments the count of an existing key or inserts it with count 1; dec(key) decrements the count of a key (guaranteed present) and removes it if the count drops to 0; getMaxKey() returns any key with the largest count, or the empty string if empty; getMinKey() returns any key with the smallest count, or the empty string if empty.
Open official problem prompt ↗Track integer counts for many keys and instantly report a key with the highest and lowest count, all in constant time.
Like ranked shelves numbered by score: each shelf holds all keys sharing that score, shelves sit in order, and bumping a key's score just slides it to the neighbouring shelf.
- Input
- inc('hello'); inc('hello'); getMaxKey(); getMinKey(); inc('leet'); getMaxKey(); getMinKey()
- Output
- 'hello'; 'hello'; 'hello'; 'leet'
- Why
- After two incs, hello has count 2 (both max and min). Adding leet (count 1) makes hello the max and leet the min.
1 <= key.length <= 10key consists of lowercase English lettersAt most 5 * 10^4 calls totaldec is only called on an existing keyEach operation must run in O(1) average time