C++ 1670.cpp
class FrontMiddleBackQueue
{
// the test cases are fairly small, maybe a simple deque with generic insert/erase would suffice
// nevertheless, let's write a proper solution
list<int> data;
list<int>::iterator middle;
public:
FrontMiddleBackQueue()
{
middle = data.begin(); // == data.end()
}
void pushFront(int val)
{
data.push_front(val);
if (data.size() <= 1)
middle = data.begin();
else if (data.size() % 2 == 0)
middle--;
}
void pushMiddle(int val)
{
if (data.size() <= 1)
{
middle = data.insert(data.begin(), val);
}
else
{
if (data.size() % 2 == 0)
middle++;
middle = data.insert(middle, val);
}
}
void pushBack(int val)
{
data.push_back(val);
if (data.size() <= 1)
middle = data.begin();
else if (data.size() % 2 == 1)
middle++;
}
int popFront()
{
if (data.empty())
return -1;
int result = data.front();
if (data.size() % 2 == 0)
middle++;
data.pop_front();
return result;
}
int popMiddle()
{
if (data.empty())
return -1;
int result = *middle;
middle = data.erase(middle);
if (data.size() % 2 == 0 && !data.empty())
middle--;
return result;
}
int popBack()
{
if (data.empty())
return -1;
int result = data.back();
if (data.size() % 2 == 1)
middle--;
data.pop_back();
return result;
}
};
Difficulty
and has an acceptance rate of about 58% (80k+ submissions).
Typical patterns to solve this problem:
- Array
- Data Stream
- Design
- Doubly Linked List
- Linked List
- Queue
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The class implements a double-ended queue that also supports insertion and removal at the exact middle position. Internally it stores the elements in a std::list<int> named data and keeps an iterator middle that always points to the current middle element according to the problem’s definition. All public operations adjust middle so that subsequent operations can be performed in constant time.
Construction
FrontMiddleBackQueue()
{
middle = data.begin(); // == data.end()
}
At creation the list is empty; both begin() and end() are identical, so middle is safely initialized to a valid iterator for an empty container.
pushFront
void pushFront(int val)
{
data.push_front(val);
if (data.size() <= 1)
middle = data.begin();
else if (data.size() % 2 == 0)
middle--;
}
The new element becomes the first node. When the list grows from size 0 to 1, middle is set to the sole element. For larger sizes, the parity check determines whether the middle shifts left: when the new size is even, the middle moves one step toward the front, preserving the invariant that middle points to the lower-middle element for even lengths.
pushMiddle
void pushMiddle(int val)
{
if (data.size() <= 1)
{
middle = data.insert(data.begin(), val);
}
else
{
if (data.size() % 2 == 0)
middle++;
middle = data.insert(middle, val);
}
}
If the list has zero or one element, insertion at the beginning suffices and middle is updated to the newly inserted node. For larger lists the algorithm first adjusts middle when the current size is even, moving it one step forward so that insertion occurs just before the element that will become the new middle. The insert call returns an iterator to the inserted node, which becomes the new middle.
pushBack
void pushBack(int val)
{
data.push_back(val);
if (data.size() <= 1)
middle = data.begin();
else if (data.size() % 2 == 1)
middle++;
}
Appending at the tail is straightforward. When the list transitions from empty to a single element, middle points to that element. For larger sizes, the middle shifts right only when the new size becomes odd, ensuring that middle continues to reference the lower-middle element for even lengths.
popFront
int popFront()
{
if (data.empty())
return -1;
int result = data.front();
if (data.size() % 2 == 0)
middle++;
data.pop_front();
return result;
}
If the list is empty the sentinel value -1 is returned. Before removal, the parity of the current size determines whether the middle must move right: when the size is even, removing the front element makes the list odd, and the middle index advances one step. The element at the front is then removed and its value returned.
popMiddle
int popMiddle()
{
if (data.empty())
return -1;
int result = *middle;
middle = data.erase(middle);
if (data.size() % 2 == 0 && !data.empty())
middle--;
return result;
}
When the list is non-empty, the value pointed to by middle is saved. The erase operation removes that node and yields an iterator to the element that follows the erased one (or end() if the erased node was the last). After removal, if the new size is even and the list is not empty, the middle must shift left to maintain the lower-middle invariant; this is achieved by decrementing middle.
popBack
int popBack()
{
if (data.empty())
return -1;
int result = data.back();
if (data.size() % 1 == 1) // size is odd before removal
middle--;
data.pop_back();
return result;
}
The method returns -1 for an empty list. When the size before removal is odd, deleting the last element makes the list even, so the middle moves one step toward the front. The tail element is then removed and its value returned.
Edge-case handling
The implementation explicitly checks for an empty container in each pop operation, returning -1 as a sentinel. The constructor sets middle to begin() which is also end() for an empty list, guaranteeing that subsequent dereferences never occur before a size check. In pushMiddle, the special case of size 0 or 1 avoids undefined iterator arithmetic by inserting at begin(). After popMiddle, the code guards against decrementing middle when the list becomes empty, preventing underflow of the iterator. All size-dependent adjustments use the current size before the mutation, ensuring that the parity logic aligns with the intended definition of “middle”.
Performance considerations
The choice of std::list provides constant-time insertion and deletion at any iterator position, which is essential for the middle operations that require direct access to the middle element. Maintaining a dedicated middle iterator eliminates the need to traverse the list to locate the middle on each operation, turning what would be linear work into constant-time updates. The parity checks (size() % 2) are inexpensive and guide the direction of iterator movement only when necessary, avoiding superfluous adjustments. By updating middle immediately after each mutation, the class guarantees that subsequent operations can rely on the invariant without recomputation, delivering overall amortized constant performance for all supported methods.
ELI5 - Simplified Explanation
Imagine you have a long line of toy cars. You want to keep track of the one sitting exactly in the middle so you can add or remove cars from the front, the back, or that middle spot whenever you want.
This code acts like a helper for your line of cars. It creates a special container called a list that holds all the cars in a row. It also uses a tiny marker called an iterator to always know which car is currently in the middle of the line.
When you push a car to the front, the helper adds it to the start of the line and checks if the middle marker needs to slide over to stay in the center. When you push a car to the back, it adds it to the end and shifts the marker again if necessary. If you decide to add a car to the middle, the helper finds that marker, tucks the new car right in, and updates its position.
Taking cars away works just like putting them in. When a car is removed from the front, the back, or the middle, the helper pauses to see if the total number of cars has changed. If the line becomes shorter or longer, it moves the marker so it is always pointing at the new middle car. It is like having a friend who is constantly counting the cars so that no matter what you do, you always know exactly where the middle is.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | JS | Java | Go | TS | |||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| DimitrisJim | Python | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| DimitrisJim | Python | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 641: Design Circular Deque
Solved On The Same Day
- problem 707: Design Linked List
- problem 1797: Design Authentication Manager
- problem 2050: Parallel Courses III
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality