457. Design Most Recently Used Queue

You are given a queue of size n, initially containing elements in increasing order from 1 to n. You need to design a Most Recently Used (MRU) Queue, which processes fetch requests in a unique way:

  • When the fetch(k) operation is called, the k-th element (1-indexed) in the queue is returned and moved to the end of the queue.
  • All other elements maintain their relative order.

You must implement the following:

  • MRUQueue(int n): Initializes an MRU queue with elements [1, 2, ..., n].
  • int fetch(int k): Fetches the k-th element from the queue, moves it to the end, and returns it.

The input consists of:

  • A string array containing operation names.
  • An integer array containing values for each operation.

Example 1:

Input : operations : ["MRUQueue", "fetch", "fetch", "fetch", "fetch"]

values : [8, 3, 5, 2, 8]

Output : [null, 3, 6, 2, 8]

Explanation :

MRUQueue mruQueue = new MRUQueue(8); // Queue: [1,2,3,4,5,6,7,8]

mruQueue.fetch(3); // Move 3 to end -> [1,2,4,5,6,7,8,3] -> returns 3

mruQueue.fetch(5); // Move 6 to end -> [1,2,4,5,7,8,3,6] -> returns 6

mruQueue.fetch(2); // Move 2 to end -> [1,4,5,7,8,3,6,2] -> returns 2

mruQueue.fetch(8); // Move 8 to end -> [1,4,5,7,3,6,2,8] -> returns 8

Example 2:

Input : operations : ["MRUQueue", "fetch", "fetch", "fetch"]

values : [5, 1, 1, 1]

Output : [null, 1, 2, 3]

Explanation :

MRUQueue mruQueue = new MRUQueue(5); // Queue: [1,2,3,4,5]

mruQueue.fetch(1); // Move 1 to end -> [2,3,4,5,1] -> returns 1

mruQueue.fetch(1); // Move 2 to end -> [3,4,5,1,2] -> returns 2

mruQueue.fetch(1); // Move 3 to end -> [4,5,1,2,3] -> returns 3

Now Your Turn!

Pick the correct output for the given input

Input : operations : ["MRUQueue", "fetch", "fetch", "fetch", "fetch", "fetch"]

values : [6, 6, 1, 1, 1, 1]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 2000
  • 1 <= k <= n
  • At most 2000 calls will be made to fetch.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class MRUQueue {
public:
MRUQueue(int n) {
//Your Code Goes Here
}
int fetch(int k) {
//Your Code Goes Here
}
};
 
/**
* Your MRUQueue object will be instantiated and called as such:
* MRUQueue* obj = new MRUQueue(n);
* int param_1 = obj->fetch(k);
*/
Test Case

Input:

Operations
Values