I went straight for a HashMap plus a TreeMap keyed by weight, which felt right.
Clarify the requirements and constraints first, then propose a data structure that combines a hash map for O(1) key lookup with a balanced binary search tree (or heap) keyed by weight to efficiently find and evict the highest-weight entry. Explain how you maintain the total weight and handle edge cases like updating an existing key's weight, ensuring O(log N) for both get and put.
Pro tip: Mention that you would use a self-balancing BST (e.g., red-black tree) or a skip list to guarantee O(log N) worst-case, and discuss how you would handle weight updates by removing and reinserting the entry. Also, consider if the eviction policy should be 'highest weight' or 'highest weight among least recently used' and clarify with the interviewer.
Ask about the expected size of the cache, whether weights can be updated, if there are any concurrency requirements, and confirm the eviction policy (evict the entry with the highest weight when over capacity).
Propose a hash map for O(1) key lookup and a balanced BST (or heap) keyed by weight for O(log N) insertion, deletion, and finding the max weight. Explain why a heap alone is insufficient if you need to update weights or remove arbitrary entries.
Detail how get(key) works: look up in hash map, return value. For put(key, value, weight): if key exists, update value and weight (remove old weight from BST, insert new weight); else insert into both structures. Then, while total weight > capacity, find and remove the entry with the highest weight from the BST and hash map, updating total weight.
Explain that get is O(1) and put is O(log N) due to BST operations. Discuss trade-offs: a heap gives O(log N) for insertion and O(1) for finding max, but O(N) for arbitrary deletion/update; a balanced BST gives O(log N) for all operations. Mention alternative approaches like using a Fibonacci heap or a skip list.
Address edge cases: empty cache, weight exceeding capacity, updating weight of existing key, and concurrent access (if relevant). Suggest optimizations like lazy deletion or using a doubly linked list combined with a heap for O(1) access to max if weights are static.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.