What is a data structure?
A data structure is a way of organising data so that it can be used efficiently. Choosing the right one often matters more than clever code.
Arrays and lists
Items stored in order and accessed by index.
- Fast access by position: O(1)
- Inserting in the middle is slow: O(n)
Linked lists
Each item points to the next.
- Fast insertion and deletion when you have the position
- Slow access by index: O(n)
Stacks (Last In, First Out)
Like a pile of plates. Used for undo features and function calls.
stack = []
stack.append(1)
stack.append(2)
print(stack.pop()) # 2Queues (First In, First Out)
Like a line at a ticket counter. Used for task scheduling and printing.
from collections import deque
queue = deque()
queue.append("A")
queue.append("B")
print(queue.popleft()) # AHash tables (dictionaries)
Store key-value pairs with very fast lookup: O(1) on average.
marks = {"Asha": 88, "Ravi": 72}
print(marks["Asha"])Trees
A hierarchy of nodes. A binary search tree keeps smaller values on the left and larger on the right, allowing fast search. Trees model file systems, HTML documents and databases indexes.
Graphs
Nodes connected by edges. They model maps, social networks and the internet. Common tasks are finding the shortest path and detecting connections.
How to choose
| Need | Use |
|---|---|
| Access by position | Array |
| Fast lookup by key | Hash table |
| Undo or backtracking | Stack |
| Process in arrival order | Queue |
| Hierarchical data | Tree |
| Networks and relationships | Graph |
Practice
Use a stack to check whether the brackets in a string like {[()]} are balanced.