Design Most Recently Used Queue - Problem

Design a special queue-like data structure that automatically moves the most recently accessed element to the end of the queue. Think of it as a smart queue that keeps frequently used items at the back for easier access patterns.

Your task is to implement the MRUQueue class with the following functionality:

  • MRUQueue(int n): Initializes the queue with n elements in order [1, 2, 3, ..., n]
  • int fetch(int k): Retrieves the k-th element (1-indexed) from the current queue, moves it to the end, and returns its value

Example: If you have queue [1, 2, 3, 4, 5] and call fetch(3), you get element 3, and the queue becomes [1, 2, 4, 5, 3].

This pattern is useful in cache systems, priority queues, and adaptive data structures where recently accessed items should be easily accessible.

Input & Output

example_1.py โ€” Basic Operations
$ Input: MRUQueue(8) fetch(3) fetch(5) fetch(2) fetch(8)
โ€บ Output: 3 6 2 2
๐Ÿ’ก Note: Initial: [1,2,3,4,5,6,7,8] โ†’ fetch(3) returns 3, queue: [1,2,4,5,6,7,8,3] โ†’ fetch(5) returns 6, queue: [1,2,4,5,7,8,3,6] โ†’ fetch(2) returns 2, queue: [1,4,5,7,8,3,6,2] โ†’ fetch(8) returns 2, queue: [1,4,5,7,8,3,6,2]
example_2.py โ€” Edge Position Access
$ Input: MRUQueue(5) fetch(1) fetch(5) fetch(3)
โ€บ Output: 1 5 4
๐Ÿ’ก Note: Initial: [1,2,3,4,5] โ†’ fetch(1) returns 1, queue: [2,3,4,5,1] โ†’ fetch(5) returns 1, queue: [2,3,4,5,1] โ†’ fetch(3) returns 4, queue: [2,3,5,1,4]
example_3.py โ€” Single Element
$ Input: MRUQueue(1) fetch(1) fetch(1)
โ€บ Output: 1 1
๐Ÿ’ก Note: With only one element, fetch(1) always returns 1 and the queue remains [1]

Constraints

  • 1 โ‰ค n โ‰ค 2000
  • 1 โ‰ค k โ‰ค current queue length
  • At most 2000 calls will be made to fetch
  • All values in the queue are guaranteed to be unique

Visualization

Tap to expand
MRU Queue: Library Book Shelf Analogy๐Ÿ“šLibrarianInitial Shelf:Book1Book2Book3REQUESTEDBook4Book5After fetch(3):Book1Book2Book4SHIFTEDBook5SHIFTEDBook3MOVED TO ENDBook 3 moved to end
Understanding the Visualization
1
Initial Shelf
Books are arranged in order [1,2,3,4,5] on the library shelf
2
Book Request
A patron requests the 3rd book from the left (book #3)
3
Remove Book
Librarian takes book #3 from its position, creating a gap
4
Shift Books
Remaining books slide left to fill the gap: [1,2,4,5,_]
5
Place at End
Book #3 is placed at the end for easy re-shelving: [1,2,4,5,3]
Key Takeaway
๐ŸŽฏ Key Insight: The MRU Queue simulates a "recently used" priority system where accessed elements are moved to the end, similar to how we organize frequently used items in real life for easy access.
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
23.8K Views
Medium Frequency
~15 min Avg. Time
892 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