KatInterview

432. All O`one Data Structure

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core challenge of this problem is to design a data structure that supports incrementing and decrementing the count of string keys, as well as retrieving keys with the minimum and maximum counts, all in O(1) average time complexity. A standard hash map (string -> count) allows for O(1) updates but requires O(N) time to find min/max keys, where N is the number of unique keys. This is too slow. To achieve O(1) for all operations, we need a more sophisticated structure that groups keys by their counts and maintains an ordering of these counts.

Solution

All O`one Data Structure in Python

class AllOne:

    class Node:
        """Node for the doubly linked list. Each node is a 'bucket' for keys with the same count."""
        def __init__(self, count):
            self.count = count
            self.keys = set()
            self.prev = None
            self.next = None

    def __init__(self):
        """Initializes the data structure."""
        # Sentinel nodes for the doubly linked list
        self.head = self.Node(0)
        self.tail = self.Node(0)
        self.head.next = self.tail
        self.tail.prev = self.head
        # Map from key to its node in the list
        self.key_to_node = {}

    def _insert_after(self, new_node, prev_node):
        """Helper to insert a new node after a given node."""
        next_node = prev_node.next
        prev_node.next = new_node
        new_node.prev = prev_node
        new_node.next = next_node
        next_node.prev = new_node

    def _remove_node(self, node):
        """Helper to remove a node from the list."""
        node.prev.next = node.next
        node.next.prev = node.prev

    def inc(self, key: str) -> None:
        # If key is new, its current node is the head sentinel (representing count 0)
        curr_node = self.key_to_node.get(key, self.head)
        new_count = curr_node.count + 1

        # Find or create the bucket for the new count
        next_node = curr_node.next
        if next_node.count != new_count:
            new_bucket = self.Node(new_count)
            self._insert_after(new_bucket, curr_node)
        else:
            new_bucket = next_node
        
        # Move key to the new bucket
        new_bucket.keys.add(key)
        self.key_to_node[key] = new_bucket

        # If the key existed, remove it from the old bucket
        if curr_node != self.head:
            curr_node.keys.remove(key)
            # If the old bucket is now empty, remove it
            if not curr_node.keys:
                self._remove_node(curr_node)

    def dec(self, key: str) -> None:
        # It's guaranteed that key exists
        curr_node = self.key_to_node[key]
        current_count = curr_node.count

        # Remove the key from its current bucket
        curr_node.keys.remove(key)

        if current_count == 1:
            # If count becomes 0, remove the key from the map
            del self.key_to_node[key]
        else:
            new_count = current_count - 1
            prev_node = curr_node.prev
            
            # Find or create the bucket for the new count
            if prev_node.count != new_count:
                new_bucket = self.Node(new_count)
                self._insert_after(new_bucket, prev_node)
            else:
                new_bucket = prev_node
            
            # Move key to the new bucket
            new_bucket.keys.add(key)
            self.key_to_node[key] = new_bucket
        
        # If the old bucket is now empty, remove it
        if not curr_node.keys:
            self._remove_node(curr_node)

    def getMaxKey(self) -> str:
        # Max key is in the bucket before the tail sentinel
        if self.tail.prev == self.head:
            return ""
        # Return an arbitrary key from the set
        return next(iter(self.tail.prev.keys))

    def getMinKey(self) -> str:
        # Min key is in the bucket after the head sentinel
        if self.head.next == self.tail:
            return ""
        return next(iter(self.head.next.keys))

All O`one Data Structure in Java

class AllOne {
    // Node for the doubly linked list. Each node is a "bucket" for keys with the same count.
    private class Node {
        int count;
        Set<String> keys;
        Node prev, next;

        Node(int count) {
            this.count = count;
            this.keys = new HashSet<>();
        }
    }

    private Node head, tail; // Sentinel nodes for the doubly linked list
    private Map<String, Node> keyToNode; // Map from key to its node in the list

    public AllOne() {
        // Initialize sentinel nodes and link them
        head = new Node(0);
        tail = new Node(0);
        head.next = tail;
        tail.prev = head;
        keyToNode = new HashMap<>();
    }
    
    // Helper to insert a new node after a given node
    private void insertAfter(Node newNode, Node prevNode) {
        Node nextNode = prevNode.next;
        prevNode.next = newNode;
        newNode.prev = prevNode;
        newNode.next = nextNode;
        nextNode.prev = newNode;
    }

    // Helper to remove a node from the list
    private void removeNode(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    public void inc(String key) {
        Node currNode = keyToNode.getOrDefault(key, head);
        int newCount = currNode.count + 1;

        Node nextNode = currNode.next;
        Node newBucket;

        // Find or create the bucket for the new count
        if (nextNode.count != newCount) {
            newBucket = new Node(newCount);
            insertAfter(newBucket, currNode);
        } else {
            newBucket = nextNode;
        }

        // Move key to the new bucket
        newBucket.keys.add(key);
        keyToNode.put(key, newBucket);

        // If the key existed, remove it from the old bucket
        if (currNode != head) {
            currNode.keys.remove(key);
            // If the old bucket is now empty, remove it
            if (currNode.keys.isEmpty()) {
                removeNode(currNode);
            }
        }
    }
    
    public void dec(String key) {
        // It's guaranteed that key exists
        Node currNode = keyToNode.get(key);
        int currentCount = currNode.count;

        // Remove the key from its current bucket
        currNode.keys.remove(key);

        if (currentCount == 1) {
            // If count becomes 0, remove the key from the map
            keyToNode.remove(key);
        } else {
            int newCount = currentCount - 1;
            Node prevNode = currNode.prev;
            Node newBucket;

            // Find or create the bucket for the new count
            if (prevNode.count != newCount) {
                newBucket = new Node(newCount);
                insertAfter(newBucket, prevNode);
            } else {
                newBucket = prevNode;
            }

            // Move key to the new bucket
            newBucket.keys.add(key);
            keyToNode.put(key, newBucket);
        }
        
        // If the old bucket is now empty, remove it
        if (currNode.keys.isEmpty()) {
            removeNode(currNode);
        }
    }
    
    public String getMaxKey() {
        // Max key is in the bucket before the tail sentinel
        if (tail.prev == head) {
            return "";
        }
        return tail.prev.keys.iterator().next();
    }
    
    public String getMinKey() {
        // Min key is in the bucket after the head sentinel
        if (head.next == tail) {
            return "";
        }
        return head.next.keys.iterator().next();
    }
}

All O`one Data Structure in C++

class AllOne {
private:
    // Doubly linked list node structure
    struct Node {
        int count;
        std::unordered_set<string> keys;
        Node *prev, *next;
        Node(int c) : count(c), prev(nullptr), next(nullptr) {}
    };

    Node *head, *tail; // Sentinel nodes for the doubly linked list
    std::unordered_map<string, Node*> key_to_node; // Map from key to its node in the list

    // Helper to insert a new node after a given node
    void insertAfter(Node* newNode, Node* prevNode) {
        Node* nextNode = prevNode->next;
        prevNode->next = newNode;
        newNode->prev = prevNode;
        newNode->next = nextNode;
        nextNode->prev = newNode;
    }

    // Helper to remove a node from the list
    void removeNode(Node* node) {
        node->prev->next = node->next;
        node->next->prev = node->prev;
        delete node;
    }

public:
    AllOne() {
        // Initialize sentinel nodes and link them
        head = new Node(0);
        tail = new Node(0);
        head->next = tail;
        tail->prev = head;
    }
    
    ~AllOne() {
        // Clean up all allocated nodes
        Node* curr = head;
        while (curr) {
            Node* next = curr->next;
            delete curr;
            curr = next;
        }
    }

    void inc(string key) {
        Node* currNode;
        int currentCount;

        if (key_to_node.find(key) == key_to_node.end()) {
            // If key is new, its current count is 0, and it belongs to the bucket before head->next
            currNode = head;
            currentCount = 0;
        } else {
            // If key exists, get its node and count
            currNode = key_to_node[key];
            currentCount = currNode->count;
        }

        int newCount = currentCount + 1;
        Node* nextNode = currNode->next;
        Node* newBucket;

        // Find or create the bucket for the new count
        if (nextNode->count != newCount) {
            newBucket = new Node(newCount);
            insertAfter(newBucket, currNode);
        } else {
            newBucket = nextNode;
        }

        // Move key to the new bucket
        newBucket->keys.insert(key);
        key_to_node[key] = newBucket;

        // If the key was not new, remove it from the old bucket
        if (currentCount > 0) {
            currNode->keys.erase(key);
            // If the old bucket is now empty, remove it
            if (currNode->keys.empty()) {
                removeNode(currNode);
            }
        }
    }
    
    void dec(string key) {
        // It's guaranteed that key exists
        Node* currNode = key_to_node[key];
        int currentCount = currNode->count;

        // Remove the key from its current bucket
        currNode->keys.erase(key);

        if (currentCount == 1) {
            // If count becomes 0, remove the key from the map
            key_to_node.erase(key);
        } else {
            int newCount = currentCount - 1;
            Node* prevNode = currNode->prev;
            Node* newBucket;

            // Find or create the bucket for the new count
            if (prevNode->count != newCount) {
                newBucket = new Node(newCount);
                insertAfter(newBucket, prevNode);
            } else {
                newBucket = prevNode;
            }
            
            // Move key to the new bucket
            newBucket->keys.insert(key);
            key_to_node[key] = newBucket;
        }

        // If the old bucket is now empty, remove it
        if (currNode->keys.empty()) {
            removeNode(currNode);
        }
    }
    
    string getMaxKey() {
        // Max key is in the bucket before the tail sentinel
        if (tail->prev == head) {
            return "";
        }
        return *(tail->prev->keys.begin());
    }
    
    string getMinKey() {
        // Min key is in the bucket after the head sentinel
        if (head->next == tail) {
            return "";
        }
        return *(head->next->keys.begin());
    }
};

All O`one Data Structure in TypeScript

class Node {
    public count: number;
    public keys: Set<string>;
    public prev: Node | null;
    public next: Node | null;

    constructor(count: number) {
        this.count = count;
        this.keys = new Set<string>();
        this.prev = null;
        this.next = null;
    }
}

class AllOne {
    private head: Node;
    private tail: Node;
    private keyToNode: Map<string, Node>;

    constructor() {
        this.head = new Node(0);
        this.tail = new Node(0);
        this.head.next = this.tail;
        this.tail.prev = this.head;
        this.keyToNode = new Map<string, Node>();
    }

    private insertAfter(newNode: Node, prevNode: Node): void {
        const nextNode = prevNode.next!;
        prevNode.next = newNode;
        newNode.prev = prevNode;
        newNode.next = nextNode;
        nextNode.prev = newNode;
    }

    private removeNode(node: Node): void {
        node.prev!.next = node.next;
        node.next!.prev = node.prev;
    }

    inc(key: string): void {
        const currNode = this.keyToNode.get(key) || this.head;
        const newCount = currNode.count + 1;

        let newBucket: Node;
        const nextNode = currNode.next!;

        if (nextNode.count !== newCount) {
            newBucket = new Node(newCount);
            this.insertAfter(newBucket, currNode);
        } else {
            newBucket = nextNode;
        }

        newBucket.keys.add(key);
        this.keyToNode.set(key, newBucket);

        if (currNode !== this.head) {
            currNode.keys.delete(key);
            if (currNode.keys.size === 0) {
                this.removeNode(currNode);
            }
        }
    }

    dec(key: string): void {
        const currNode = this.keyToNode.get(key)!;
        const currentCount = currNode.count;

        currNode.keys.delete(key);

        if (currentCount === 1) {
            this.keyToNode.delete(key);
        } else {
            const newCount = currentCount - 1;
            const prevNode = currNode.prev!;
            let newBucket: Node;

            if (prevNode.count !== newCount) {
                newBucket = new Node(newCount);
                this.insertAfter(newBucket, prevNode);
            } else {
                newBucket = prevNode;
            }

            newBucket.keys.add(key);
            this.keyToNode.set(key, newBucket);
        }

        if (currNode.keys.size === 0) {
            this.removeNode(currNode);
        }
    }

    getMaxKey(): string {
        if (this.tail.prev === this.head) {
            return "";
        }
        return this.tail.prev!.keys.values().next().value;
    }

    getMinKey(): string {
        if (this.head.next === this.tail) {
            return "";
        }
        return this.head.next!.keys.values().next().value;
    }
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.