Design Most Recently Used Queue - Problem
Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the MRUQueue class:
MRUQueue(int n)constructs the MRUQueue withnelements:[1,2,3,...,n].int fetch(int k)moves the kth element (1-indexed) to the end of the queue and returns it.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["MRUQueue", "fetch", "fetch", "fetch"], values = [3, 1, 2, 3]
›
Output:
[1, 2, 3]
💡 Note:
MRUQueue(3) creates [1,2,3]. fetch(1) returns 1, queue becomes [2,3,1]. fetch(2) returns 3, queue becomes [2,1,3]. fetch(3) returns 3, queue becomes [2,1,3].
Example 2 — Repeated Fetch
$
Input:
operations = ["MRUQueue", "fetch", "fetch"], values = [2, 2, 1]
›
Output:
[2, 1]
💡 Note:
MRUQueue(2) creates [1,2]. fetch(2) returns 2, queue becomes [1,2]. fetch(1) returns 1, queue becomes [2,1].
Example 3 — Single Element
$
Input:
operations = ["MRUQueue", "fetch"], values = [1, 1]
›
Output:
[1]
💡 Note:
MRUQueue(1) creates [1]. fetch(1) returns 1, queue remains [1].
Constraints
- 1 ≤ n ≤ 2000
- 1 ≤ k ≤ current queue length
- At most 2000 calls will be made to fetch
Visualization
Tap to expand
Understanding the Visualization
1
Input
Queue [1,2,3,4,5] and fetch(3)
2
Process
Move element at position 3 to end
3
Output
Return 3, queue becomes [1,2,4,5,3]
Key Takeaway
🎯 Key Insight: Choose data structure that minimizes movement cost - linked list beats array
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code