Practice/Google/Leetcode 1756. Design Most Recently Used Queue
CodingMust
Design a special queue data structure that maintains elements in order of their most recent access. The queue should support two primary operations:
The queue is initialized with a capacity parameter n, though the actual number of elements may vary based on operations performed.
The key challenge is implementing the fetch operation efficiently. When you fetch an element at position k, you must return its value and reposition it to the end of the queue, shifting other elements as needed.
MRUQueue(n) that initializes the queue with capacity nenqueue(val) to add a value to the end of the queuefetch(k) to return the element at position k (1-indexed) and move it to the endfetch(k) operation, the fetched element should be at the most recent position (end)Example 1:
` Operations: MRUQueue mru = new MRUQueue(5) mru.enqueue(10) mru.enqueue(20) mru.enqueue(30) mru.fetch(2)
Output: 20 Explanation:
Example 2:
` Operations: MRUQueue mru = new MRUQueue(3) mru.enqueue(5) mru.enqueue(10) mru.enqueue(15) mru.fetch(3) mru.fetch(2)
Output: fetch(3) returns 15, fetch(2) returns 10 Explanation:
Example 3:
` Operations: MRUQueue mru = new MRUQueue(4) mru.enqueue(1) mru.enqueue(2) mru.enqueue(3) mru.fetch(1) mru.enqueue(4) mru.fetch(2)
Output: fetch(1) returns 1, fetch(2) returns 3 Explanation: