What is a Data Structure?
A data structure is a way of organising and storing data in memory so that it can be accessed and modified efficiently.
Think of it like containers in a kitchen. A spice rack, a refrigerator, a drawer — each stores things differently because the way you use them is different. You don't store ice cream in a spice rack. You pick the right container for the job.
Data structures are the same idea. The type of operations you need determines which data structure to use.
Why Do They Matter?
Imagine you need to find a contact in your phone. If the contacts were stored in a random pile (unsorted array), you'd have to check each one until you found it — slow. But because they're stored alphabetically (sorted), you can jump to the right letter instantly — fast.
The data structure determines the cost of your operations. Choosing the wrong one can make a fast program slow — or make an impossible program possible.
The Big Categories
Data structures split into two families:
Linear — elements arranged in a sequence, one after another.
| Structure | Access | Insert/Delete | Use When |
|---|---|---|---|
| Array | O(1) | O(n) | You need fast index access |
| Linked List | O(n) | O(1) at head | You insert/delete frequently |
| Stack | O(n) | O(1) | Last-in, first-out order |
| Queue | O(n) | O(1) | First-in, first-out order |
Non-linear — elements connected with relationships, not a single sequence.
| Structure | Use When |
|---|---|
| Tree | Hierarchical data (file system, DOM) |
| Graph | Network of connections (maps, social networks) |
| Hash Map | Fast key-value lookup (O(1) average) |
| Heap | Always need min/max quickly |
A Concrete Example
Say you're building a browser's back button. Every time you visit a page, push it onto a stack. When you press back, pop from the stack.
An array would work here, but a stack communicates your intent clearly: only the top matters.
Arrays — The Simplest Linear Structure
Arrays store elements in contiguous memory. Index 0 is the first element, index n-1 is the last.
Hash Maps — The Power of O(1) Lookup
A hash map stores key-value pairs. It uses a hash function to convert your key into an array index. This gives you average O(1) insert, delete, and lookup.
| Key | Value |
|---|---|
| apple | 12 |
| banana | 45 |
| cherry | 89 |
| orange | 56 |
How to Pick the Right One
Ask yourself three questions:
- What operations do you need? Insertion, deletion, search, or min/max access?
- How often? Operations that happen millions of times need to be as fast as possible.
- What are the trade-offs? Faster lookup often means more memory.
There's no universally "best" data structure. A hash map is terrible for finding the minimum element. A sorted array is terrible for frequent insertions. The right choice depends entirely on your use case.
As you work through this roadmap, you'll develop intuition for this. Each data structure has a personality — you'll start to feel when something fits.