I have implemented the design a LRU Cache Problem on LeetCode using the conventional method (Doubly Linked List+Hash Map). For those unfamiliar with the problem, this implementation looks something like this:
I understand why this method is used (quick removal/insertion at both ends, fast access in the middle). What I am failing to understand is why someone would use both a HashMap and a LinkedList when one could simply use a array-based deque (in Java ArrayDeque, C++ simply deque). This deque allows for ease of insertion/deletion at both ends, and quick access in the middle which is exactly what you need for an LRU cache. You also would use less space because you wouldn't need to store a pointer to each node.
Is there a reason why the LRU cache is almost universally designed (on most tutorials at least) using the latter method as opposed to the Deque/ArrayDeque method? Would the HashMap/LinkedList method have any benefits?
stack
,queue
,deque
at the same time, apart fromlinked list
anddoubly linked list
, so it's very handy. For example Java'sLinkedList
is such an implementation. Actually, when you try to implstack
andqueue
, you will found most of the operations could be done simply by wrapping operations from a well-implemented doubly linked list. – UbanaArrayDeque
is array-based, then you can't remove from both end at O(1), at least one of them is not. If it's not array-based, why it's calledArrayDeque
? – Ubanamove_to_end
operation, then you have probably written a FIFO cache and not an LRU cache. – SystematistIn [case of elements deleted from the head of an ArrayDeque] only part of the array is usable
The indices used wrap around at the current size. – Costar