# Leetcode 1767 Solution

https://leetcode.com/problems/design-front-middle-back-queue

## Solution

``````class FrontMiddleBackQueue:

def __init__(self):
self.q1 = deque()
self.q2 = deque()

def balance(self):
while len(self.q1) > len(self.q2):
self.q2.appendleft(self.q1.pop())

while len(self.q1) + 1 < len(self.q2):
self.q1.append(self.q2.popleft())

def pushFront(self, val: int) -> None:
self.q1.appendleft(val)
self.balance()

def pushMiddle(self, val: int) -> None:
self.q1.append(val)
self.balance()

def pushBack(self, val: int) -> None:
self.q2.append(val)
self.balance()

def popFront(self) -> int:
ans = None

if len(self.q1):
ans = self.q1.popleft()
elif len(self.q2):
ans = self.q2.popleft()
else:
ans = -1

self.balance()
return ans

def popMiddle(self) -> int:
ans = None

if len(self.q2) == 0:
ans = -1
elif len(self.q1) == len(self.q2):
ans = self.q1.pop()
else:
ans = self.q2.popleft()

self.balance()
return ans

def popBack(self) -> int:
ans = None

if len(self.q2):
ans = self.q2.pop()
else:
ans = -1

self.balance()
return ans

# Your FrontMiddleBackQueue object will be instantiated and called as such:
# obj = FrontMiddleBackQueue()
# obj.pushFront(val)
# obj.pushMiddle(val)
# obj.pushBack(val)
# param_4 = obj.popFront()
# param_5 = obj.popMiddle()
# param_6 = obj.popBack()
``````