Design Front Middle Back Queue
Design Front Middle Back Queue is a medium design data structures problem solved with the linked lists pattern.
The best approach, optimal (two balanced deques), runs in O(1) per operation time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from one list up.
Problem
Design a queue that supports push and pop at the front, the middle and the back. When there are two middle positions, use the one closer to the front.
Examples
Example 1
- Input
pushFront(1); pushBack(2); pushMiddle(3); pushMiddle(4); popFront(); popMiddle(); popMiddle(); popBack(); popFront()- Output
1, 3, 4, 2, -1- Why
- After the pushes the queue is [1, 4, 3, 2].
Constraints
- Up to 1000 calls; pops on an empty queue return -1.
- With two middles, pushMiddle goes to the front one and popMiddle takes the front one.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (1 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| One list | O(n) per operation | O(n) |
| Optimal (two balanced deques) | O(1) per operation | O(n) |
1One list
O(n) per operationO(n)Use a single ArrayList and insert or remove at index 0, size / 2 or the end.
- pushMiddle at size / 2; popMiddle at (size - 1) / 2.
class FrontMiddleBackQueue {
private final List<Integer> a = new ArrayList<>();
public void pushFront(int val) { a.add(0, val); }
public void pushMiddle(int val) { a.add(a.size() / 2, val); }
public void pushBack(int val) { a.add(val); }
public int popFront() { return a.isEmpty() ? -1 : a.remove(0); }
public int popMiddle() { return a.isEmpty() ? -1 : a.remove((a.size() - 1) / 2); }
public int popBack() { return a.isEmpty() ? -1 : a.remove(a.size() - 1); }
}class FrontMiddleBackQueue:
def __init__(self):
self.a = []
def pushFront(self, val: int) -> None:
self.a.insert(0, val)
def pushMiddle(self, val: int) -> None:
self.a.insert(len(self.a) // 2, val)
def pushBack(self, val: int) -> None:
self.a.append(val)
def popFront(self) -> int:
return -1 if not self.a else self.a.pop(0)
def popMiddle(self) -> int:
return -1 if not self.a else self.a.pop((len(self.a) - 1) // 2)
def popBack(self) -> int:
return -1 if not self.a else self.a.pop()class FrontMiddleBackQueue {
vector<int> a;
public:
void pushFront(int val) { a.insert(a.begin(), val); }
void pushMiddle(int val) { a.insert(a.begin() + a.size() / 2, val); }
void pushBack(int val) { a.push_back(val); }
int popFront() {
if (a.empty()) return -1;
int v = a.front();
a.erase(a.begin());
return v;
}
int popMiddle() {
if (a.empty()) return -1;
int i = (a.size() - 1) / 2;
int v = a[i];
a.erase(a.begin() + i);
return v;
}
int popBack() {
if (a.empty()) return -1;
int v = a.back();
a.pop_back();
return v;
}
};class FrontMiddleBackQueue {
constructor() { this.a = []; }
pushFront(val) { this.a.unshift(val); }
pushMiddle(val) { this.a.splice(Math.floor(this.a.length / 2), 0, val); }
pushBack(val) { this.a.push(val); }
popFront() { return this.a.length === 0 ? -1 : this.a.shift(); }
popMiddle() { return this.a.length === 0 ? -1 : this.a.splice(Math.floor((this.a.length - 1) / 2), 1)[0]; }
popBack() { return this.a.length === 0 ? -1 : this.a.pop(); }
}2Optimal (two balanced deques)
O(1) per operationO(n)left holds the front half, right holds the back half, with right.size() == left.size() or left.size() + 1. After every operation, rebalance by moving one element across the boundary. The middle (the front one of two middles) is then left's last element when the sizes are equal, otherwise right's first.
- balance(): if left.size() > right.size(), move left.last to right.first; if right.size() > left.size() + 1, move right.first to left.last.
- pushMiddle: if the halves are equal in size, the new value becomes right's first; otherwise it becomes left's last.
- popMiddle: equal sizes → left's last; otherwise right's first.
class FrontMiddleBackQueue {
private final Deque<Integer> left = new ArrayDeque<>(), right = new ArrayDeque<>();
// invariant: right.size() == left.size() or left.size() + 1
private void balance() {
if (left.size() > right.size()) right.addFirst(left.pollLast());
else if (right.size() > left.size() + 1) left.addLast(right.pollFirst());
}
public void pushFront(int val) { left.addFirst(val); balance(); }
public void pushMiddle(int val) {
if (left.size() == right.size()) right.addFirst(val);
else left.addLast(val);
}
public void pushBack(int val) { right.addLast(val); balance(); }
public int popFront() {
if (right.isEmpty()) return -1;
int v = left.isEmpty() ? right.pollFirst() : left.pollFirst();
balance();
return v;
}
public int popMiddle() {
if (right.isEmpty()) return -1;
int v = left.size() == right.size() ? left.pollLast() : right.pollFirst();
balance();
return v;
}
public int popBack() {
if (right.isEmpty()) return -1;
int v = right.pollLast();
balance();
return v;
}
}class FrontMiddleBackQueue:
def __init__(self):
self.left = deque()
self.right = deque()
# invariant: len(right) == len(left) or len(left) + 1
def balance(self) -> None:
if len(self.left) > len(self.right):
self.right.appendleft(self.left.pop())
elif len(self.right) > len(self.left) + 1:
self.left.append(self.right.popleft())
def pushFront(self, val: int) -> None:
self.left.appendleft(val)
self.balance()
def pushMiddle(self, val: int) -> None:
if len(self.left) == len(self.right):
self.right.appendleft(val)
else:
self.left.append(val)
def pushBack(self, val: int) -> None:
self.right.append(val)
self.balance()
def popFront(self) -> int:
if not self.right:
return -1
v = self.right.popleft() if not self.left else self.left.popleft()
self.balance()
return v
def popMiddle(self) -> int:
if not self.right:
return -1
v = self.left.pop() if len(self.left) == len(self.right) else self.right.popleft()
self.balance()
return v
def popBack(self) -> int:
if not self.right:
return -1
v = self.right.pop()
self.balance()
return vclass FrontMiddleBackQueue {
deque<int> left, right;
// invariant: right.size() == left.size() or left.size() + 1
void balance() {
if (left.size() > right.size()) { right.push_front(left.back()); left.pop_back(); }
else if (right.size() > left.size() + 1) { left.push_back(right.front()); right.pop_front(); }
}
public:
void pushFront(int val) { left.push_front(val); balance(); }
void pushMiddle(int val) {
if (left.size() == right.size()) right.push_front(val);
else left.push_back(val);
}
void pushBack(int val) { right.push_back(val); balance(); }
int popFront() {
if (right.empty()) return -1;
int v;
if (left.empty()) { v = right.front(); right.pop_front(); }
else { v = left.front(); left.pop_front(); }
balance();
return v;
}
int popMiddle() {
if (right.empty()) return -1;
int v;
if (left.size() == right.size()) { v = left.back(); left.pop_back(); }
else { v = right.front(); right.pop_front(); }
balance();
return v;
}
int popBack() {
if (right.empty()) return -1;
int v = right.back();
right.pop_back();
balance();
return v;
}
};class FrontMiddleBackQueue {
constructor() {
this.left = [];
this.right = [];
}
// invariant: right.length === left.length or left.length + 1
balance() {
if (this.left.length > this.right.length) this.right.unshift(this.left.pop());
else if (this.right.length > this.left.length + 1) this.left.push(this.right.shift());
}
pushFront(val) { this.left.unshift(val); this.balance(); }
pushMiddle(val) {
if (this.left.length === this.right.length) this.right.unshift(val);
else this.left.push(val);
}
pushBack(val) { this.right.push(val); this.balance(); }
popFront() {
if (this.right.length === 0) return -1;
const v = this.left.length === 0 ? this.right.shift() : this.left.shift();
this.balance();
return v;
}
popMiddle() {
if (this.right.length === 0) return -1;
const v = this.left.length === this.right.length ? this.left.pop() : this.right.shift();
this.balance();
return v;
}
popBack() {
if (this.right.length === 0) return -1;
const v = this.right.pop();
this.balance();
return v;
}
}Edge cases to test
- popMiddle on an even-length queue
- Operations on an empty queue
Hints
Hint 1
Split the queue into two deques, left and right, keeping left.size() equal to right.size() or one less. The middle is then always at the boundary.
FAQ
What is the best time complexity for Design Front Middle Back Queue?
Optimal (two balanced deques) runs in O(1) per operation time and O(n) extra space.
Which pattern does Design Front Middle Back Queue use?
It is a design data structures problem that uses the linked lists pattern. Other problems with the same pattern: Design Linked List, LRU Cache, All O`one Data Structure.
Is there a brute force solution for Design Front Middle Back Queue?
Yes. One list takes O(n) per operation time and O(n) space. Use a single ArrayList and insert or remove at index 0, size / 2 or the end.
Which edge cases should I test for Design Front Middle Back Queue?
popMiddle on an even-length queue; Operations on an empty queue.