Design Most Recently Used Queue
We’ll implement the MRUQueue
class using a list as the underlying data structure. The __init__
method initializes the queue with n
elements, and the fetch
method takes the k
-th element from the queue, moves it to the end, and returns it.
Here’s the code:
|
|
Explanation:
The
__init__
method initializes the queue with a list containing integers from 1 ton
.The
fetch
method fetches thek
-th element, appends it to the end of the queue, and removes it from its original position. Since the inputk
is 1-indexed, we adjust it to 0-indexed when accessing the list.By using the
append
method to add the element to the end andpop
method to remove it from the original position, we’re ensuring the MRU (Most Recently Used) element is moved to the end of the queue.
The given code meets the problem’s constraints and provides the desired functionality for the MRUQueue class.