Data Structures
Fundamental ways to organize and store data for efficient access and modification.
What is a Data Structure?
A data structure is a way of organizing data so that it can be used efficiently. Different data structures are suited for different tasksโchoosing the right one can dramatically improve your program's performance.
๐ฏ Key Categories
Arrays, Linked Lists, Stacks, Queues
Trees, Graphs, Heaps
๐ฆ Arrays
An array stores elements in contiguous memory locations. Access any element instantly by its index.
โ Strengths
- โข O(1) random access by index
- โข Cache-friendly (memory locality)
- โข Simple and fast
โ Weaknesses
- โข Fixed size (in many languages)
- โข O(n) insertion/deletion
- โข Expensive to resize
// Array operations const arr = [1, 2, 3, 4, 5]; arr[0]; // Access: O(1) arr.push(6); // Append: O(1) amortized arr.splice(2, 1); // Delete at index: O(n)
๐ Linked List
A linked list stores elements in nodes, where each node points to the next. Great for frequent insertions/deletions.
โ Strengths
- โข O(1) insertion/deletion at known position
- โข Dynamic size
- โข No wasted memory
โ Weaknesses
- โข O(n) access (must traverse)
- โข Extra memory for pointers
- โข Poor cache performance
๐ Stack (LIFO)
Last In, First Out โ like a stack of plates. You can only add or remove from the top.
Use cases: Function call stack, undo operations, expression parsing, browser history (back button)
// Stack operations - all O(1) const stack = []; stack.push(1); // Add to top stack.push(2); stack.pop(); // Remove from top โ 2 stack[stack.length - 1]; // Peek top โ 1
๐ซ Queue (FIFO)
First In, First Out โ like a line at a store. Add to the back, remove from the front.
Use cases: Task scheduling, BFS traversal, print queue, message queues
๐ Hash Table
Maps keys to values using a hash function. Provides near-instant O(1) lookup!
// Hash table operations - all O(1) average
const map = new Map();
map.set("name", "Alice"); // Insert
map.get("name"); // Lookup โ "Alice"
map.has("name"); // Check โ true
map.delete("name"); // Remove๐ณ Tree
A hierarchical structure with a root node and child nodes. Each node can have multiple children but only one parent.
Common types: Binary Tree, Binary Search Tree (BST), AVL Tree, Red-Black Tree, Trie, Heap
๐ Graph
A collection of nodes (vertices) connected by edges. Can represent networks, relationships, maps, and more.
Directed Graph
Edges have direction (A โ B)
Example: Twitter follows
Undirected Graph
Edges go both ways (A โ B)
Example: Facebook friends
Quick Comparison
| Structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) |
| Linked List | O(n) | O(n) | O(1)* | O(1)* |
| Hash Table | O(1) | O(1) | O(1) | O(1) |
| BST (balanced) | O(log n) | O(log n) | O(log n) | O(log n) |
* O(1) when position is known; O(n) to find position
Content adapted from Hello ็ฎๆณ - Data Structures by Krahets, licensed under CC BY-NC-SA 4.0.