1. Brute Force — Dynamic Array with Inefficient Shift
Intuition
Store elements in a list. When an element is removed from the front, shift all remaining elements left to maintain index 0 as head.
Algorithm
- Step 1: On enQueue(x), append x if size < K.
- Step 2: On deQueue(), remove element at index 0 and shift subsequent elements left.
- Step 3: Front is at index 0, Rear is at index size - 1.
#include <iostream>#include <vector> using namespace std; class MyCircularQueue {private: vector<int> data; int capacity;public: MyCircularQueue(int k) : capacity(k) {} bool enQueue(int value) { if (data.size() == capacity) return false; data.push_back(value); return true; } bool deQueue() { if (data.empty()) return false; data.erase(data.begin()); return true; } int Front() { return data.empty() ? -1 : data.front(); } int Rear() { return data.empty() ? -1 : data.back(); } bool isEmpty() { return data.empty(); } bool isFull() { return data.size() == capacity; }}; int main() { MyCircularQueue q(3); cout << q.enQueue(1) << endl; // 1 cout << q.enQueue(2) << endl; // 1 cout << q.enQueue(3) << endl; // 1 cout << q.enQueue(4) << endl; // 0 (full) cout << q.Rear() << endl; // 3 cout << q.deQueue() << endl; // 1 cout << q.enQueue(4) << endl; // 1 cout << q.Rear() << endl; // 4 return 0;}Time & Space Complexity
- Time complexity:
enQueue: O(1), deQueue: O(N)— Shifting elements left on every dequeue takes O(N) linear time. - Space complexity:
O(K)— Stores at most K elements in array.
Why Brute Force Doesn't Scale:
In real-time audio/packet processing, dynamic allocation or O(N) copying causes audio stuttering or packet loss.
Fixed array ring buffers process millions of operations per second with microsecond predictability.