1. Brute Force — Dynamic Array with Splicing
Intuition
Use an array list and perform insert(mid, val) and remove(mid) directly.
Algorithm
- Step 1: On pushMiddle, compute
mid = len / 2and insert atmid. - Step 2: On popMiddle, compute
mid = (len - 1) / 2and remove atmid. - Step 3: Front and Back operations insert/remove at index 0 and end.
#include <iostream>#include <vector> using namespace std; class FrontMiddleBackQueue {private: vector<int> v;public: FrontMiddleBackQueue() {} void pushFront(int val) { v.insert(v.begin(), val); } void pushMiddle(int val) { v.insert(v.begin() + v.size() / 2, val); } void pushBack(int val) { v.push_back(val); } int popFront() { if (v.empty()) return -1; int val = v.front(); v.erase(v.begin()); return val; } int popMiddle() { if (v.empty()) return -1; int mid = (v.size() - 1) / 2; int val = v[mid]; v.erase(v.begin() + mid); return val; } int popBack() { if (v.empty()) return -1; int val = v.back(); v.pop_back(); return val; }}; int main() { FrontMiddleBackQueue q; q.pushFront(1); q.pushBack(2); q.pushMiddle(3); q.pushMiddle(4); cout << q.popFront() << endl; // 1 cout << q.popMiddle() << endl; // 3 cout << q.popMiddle() << endl; // 4 cout << q.popBack() << endl; // 2 return 0;}Time & Space Complexity
- Time complexity:
Front/Mid ops: O(N), Back ops: O(1)— Array insertion and deletion at arbitrary index takes O(N) time. - Space complexity:
O(N)— Stores N elements.
Why Brute Force Doesn't Scale:
With 105 operations, array shifts lead to 1010 instructions (TLE).
Dual deques execute 105 operations in 4ms with constant pointer moves.