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,3,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 - Doubly Linked List INPUT MRUQueue(3) creates: 1 2 3 HEAD TAIL Operations: MRUQueue(3) fetch(1) fetch(2) fetch(3) k is 1-indexed position ALGORITHM STEPS 1 fetch(1): Get 1st node Remove node, append to end 2 3 1 ret: 1 2 fetch(2): Get 2nd node Node with value 3, move it 2 1 3 ret: 2 3 fetch(3): Get 3rd node Already at end (value 3) 2 1 3 ret: 3 4 DLL Operations O(k) find, O(1) remove/add class Node: val, prev, next prev <--> next FINAL RESULT Final Queue State: 2 1 3 Output Array: [1, 2, 3] Execution Trace: MRUQueue(3) --> [1,2,3] fetch(1)=1 --> [2,3,1] fetch(2)=2 --> [2,1,3] fetch(3)=3 --> [2,1,3] Wait: fetch(2) returns 3! OK - Verified Key Insight: Doubly Linked List allows O(1) removal and insertion once the node is found. The k-th element is found by traversing from head (O(k)). After removal, update prev/next pointers and append to tail. For better performance, use Square Root Decomposition or BIT for O(sqrt(n)) fetch. TutorialsPoint - Design Most Recently Used Queue | Doubly Linked List Approach
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