LeetCode 1756: Design Most Recently Used Queue
LeetCode 1756 Solution Explanation
Explanation:
To design a Most Recently Used (MRU) queue, we can use a combination of a doubly linked list and a hashmap. The doubly linked list will store the elements in the order of their most recent usage, and the hashmap will store the mapping of the element value to its corresponding node in the linked list.
The key operations we need to support are:
put(int key, int value)
: Add or update an element in the queue. If the element already exists, we update its value and move it to the front of the queue.get(int key)
: Retrieve the value of the element with the given key. If the element exists, we move it to the front of the queue.
By maintaining a doubly linked list and a hashmap, we can achieve constant time complexity for both put
and get
operations.
:
LeetCode 1756 Solutions in Java, C++, Python
import java.util.HashMap;
class Node {
int key, value;
Node prev, next;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
class MRUQueue {
private final int capacity;
private final HashMap<Integer, Node> map;
private Node head, tail;
public MRUQueue(int capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
this.head = new Node(-1, -1);
this.tail = new Node(-1, -1);
head.next = tail;
tail.prev = head;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
Node node = map.get(key);
node.value = value;
moveToFront(node);
} else {
if (map.size() == capacity) {
evict();
}
Node newNode = new Node(key, value);
map.put(key, newNode);
addToFront(newNode);
}
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}
Node node = map.get(key);
moveToFront(node);
return node.value;
}
private void addToFront(Node node) {
node.next = head.next;
node.prev = head;
head.next.prev = node;
head.next = node;
}
private void moveToFront(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
addToFront(node);
}
private void evict() {
Node toRemove = tail.prev;
map.remove(toRemove.key);
tail.prev = toRemove.prev;
toRemove.prev.next = tail;
}
}
Interactive Code Editor for LeetCode 1756
Improve Your LeetCode 1756 Solution
Use the editor below to refine the provided solution for LeetCode 1756. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...