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 with n elements: [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
Most Recently Used Queue OperationInput Queue: [1, 2, 3, 4, 5]12345pos 1pos 2pos 3pos 4pos 5fetch(3)After fetch(3): [1, 2, 4, 5, 3]12453moved to endReturn: 3Element 3 becomes most recently used
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
Asked in
Google 15 Amazon 12 Facebook 8
23.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen