#1670
Medium Algorithms Design front middle back queue
Array Linked List Design Queue Doubly-Linked List Data Stream
56.9% acceptance
Feb 23, 2026
815
114
Design a queue that supports push and pop operations in the front, middle, and back.
FrontMiddleBack() Initializes the queue.
void pushFront(int val) Adds val to the front of the queue.
void pushMiddle(int val) Adds val to the middle of the queue.
void pushBack(int val) Adds val to the back of the queue.
int popFront() Removes the front element and returns it. If empty, return -1.
int popMiddle() Removes the middle element and returns it. If empty, return -1.
int popBack() Removes the back element and returns it. If empty, return -1.
When there are two middle positions, use the frontmost.
Example:
["FrontMiddleBackQueue","pushFront","pushBack","pushMiddle","pushMiddle",
"popFront","popMiddle","popMiddle","popBack","popFront"]
[[],[1],[2],[3],[4],[],[],[],[],[]]
Output: [null,null,null,null,null,1,3,4,2,-1]
Solution
Rust
Time O(2^n)
Space O(n)
pub struct FrontMiddleBackQueue {
data: Vec<i32>,
}
impl FrontMiddleBackQueue {
pub fn new() -> Self {
FrontMiddleBackQueue { data: Vec::new() }
}
pub fn push_front(&mut self, val: i32) {
self.data.insert(0, val);
}
pub fn push_middle(&mut self, val: i32) {
let mid = self.data.len() / 2;
self.data.insert(mid, val);
}
pub fn push_back(&mut self, val: i32) {
self.data.push(val);
}
pub fn pop_front(&mut self) -> i32 {
if self.data.is_empty() { -1 } else { self.data.remove(0) }
}
pub fn pop_middle(&mut self) -> i32 {
if self.data.is_empty() {
-1
} else {
let mid = (self.data.len() - 1) / 2;
self.data.remove(mid)
}
}
pub fn pop_back(&mut self) -> i32 {
self.data.pop().unwrap_or(-1)
}
}