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 withnelements 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code