← Pinduoduo Interview Insights
The question itself is fine if you've seen it before.
Start by clarifying the requirements: O(1) get and put, capacity limit, and eviction policy (least recently used). Then propose a combination of a hash map for O(1) access and a doubly linked list for O(1) updates to recency order, explaining how they work together.
Pro tip: Mention that you would use a doubly linked list with dummy head and tail nodes to simplify edge cases, and discuss thread-safety if the cache might be accessed concurrently.
Confirm that get returns the value if present and marks it as recently used, put inserts or updates and evicts the least recently used item when capacity is exceeded. Ask about capacity bounds, concurrency, and whether null values are allowed.
Use a hash map (dictionary) to store key -> node references for O(1) lookup, and a doubly linked list to maintain the order of usage, where the head is most recently used and the tail is least recently used.
Each node stores key, value, prev, and next pointers. For get: if key exists, move node to head and return value; else return -1. For put: if key exists, update value and move to head; else create new node, add to head, and if capacity exceeded, remove tail node and delete its key from the map.
Use dummy head and tail nodes to avoid null checks. Ensure that when evicting, you remove the key from the hash map as well. Discuss potential concurrency issues and solutions like locks or concurrent data structures if needed.
Explain that both get and put run in O(1) average time due to hash map and linked list operations. Walk through a small example to verify correctness, and mention testing edge cases like capacity 1, repeated gets, and eviction order.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.