#1756
Medium Algorithms Design most recently used queue
Array Linked List Divide and Conquer Design Simulation Doubly-Linked List
78.3% acceptance
Mar 31, 2026
338
28
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.
Solution
Rust
Time O(1)
Space O(1)
struct MRUQueue {
data: Vec<i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MRUQueue {
fn new(n: i32) -> Self {
MRUQueue { data: (1..=n).collect() }
}
fn fetch(&mut self, k: i32) -> i32 {
let idx = (k - 1) as usize;
let val = self.data.remove(idx);
self.data.push(val);
val
}
}
/*
* Your MRUQueue object will be instantiated and called as such:
* let obj = MRUQueue::new(n);
* let ret_1: i32 = obj.fetch(k);
*/