Implement LRU cache with O(1) operations

by stellar_infinity62
Microsoft
mid
coding
medium
offer
38
402

Standard LRU cache question but they wanted production-quality code.

Used a hash map + doubly linked list approach. The key insight is maintaining the list order on every get and put operation.

The interviewer asked follow up questions about thread safety. I discussed using a read-write lock where gets can be concurrent but puts need exclusive access. Also mentioned the option of using a ConcurrentHashMap with a striped lock on the linked list.

Second follow up was about what happens when the cache needs to be distributed. Talked about consistent hashing to partition the cache across multiple nodes.

Coded the solution in Python, all test cases passed. The interviewer was happy with the code quality and edge case handling.

Tip: make sure you handle the case where put updates an existing key (move to front, don't add a new node).


Markdown supported