1. Brute Force — Dynamic Array with Front Shift
Intuition
Store items in an array, pushing and unshifting directly.
Algorithm
- Step 1: On insertFront(x), unshift x at index 0 if length < k.
- Step 2: On insertLast(x), push x at end if length < k.
- Step 3: On deleteFront(), remove index 0; on deleteLast(), pop end.
#include <iostream>#include <vector> using namespace std; class MyCircularDeque {private: vector<int> arr; int cap;public: MyCircularDeque(int k) : cap(k) {} bool insertFront(int value) { if (arr.size() == cap) return false; arr.insert(arr.begin(), value); return true; } bool insertLast(int value) { if (arr.size() == cap) return false; arr.push_back(value); return true; } bool deleteFront() { if (arr.empty()) return false; arr.erase(arr.begin()); return true; } bool deleteLast() { if (arr.empty()) return false; arr.pop_back(); return true; } int getFront() { return arr.empty() ? -1 : arr.front(); } int getRear() { return arr.empty() ? -1 : arr.back(); } bool isEmpty() { return arr.empty(); } bool isFull() { return arr.size() == cap; }}; int main() { MyCircularDeque dq(3); cout << dq.insertLast(1) << endl; // 1 cout << dq.insertLast(2) << endl; // 1 cout << dq.insertFront(3) << endl; // 1 cout << dq.getFront() << endl; // 3 cout << dq.getRear() << endl; // 2 return 0;}Time & Space Complexity
- Time complexity:
Front ops: O(N), Rear ops: O(1)— Array unshift/shift operations copy all N elements. - Space complexity:
O(K)— Stores K elements.
Why Brute Force Doesn't Scale:
A stream of 105 alternating front/last operations will time out on dynamic lists.
Fixed ring buffer runs 105 operations in ~3ms.