A data structure is a way of organizing data so that the operations you care about are cheap. An algorithm is a finite, unambiguous sequence of steps that turns an input into the desired output. Together they decide whether a program answers in a millisecond or an hour, and whether it fits in memory at all. This module teaches you to look at a problem, list the operations it needs, and pick the structure and technique that make those operations fast.
Think of it like
A library and its librarian
A library owns the same books whether they are piled on the floor or shelved by call number with a catalog at the door. The pile is effortless to add to, but finding one book means checking every book. Shelves plus a catalog cost effort to maintain, yet any book is seconds away. The books are your data, the shelving and catalog are the data structure, and the procedure the librarian follows to fetch a book is the algorithm.
What data structures and algorithms are
Every program stores information and does something with it. The way information is laid out in memory (contiguously, linked by pointers, bucketed by a hash, arranged in a tree) determines which questions are cheap to ask. The algorithm is the recipe that asks and answers those questions.
- Data structure
- A concrete arrangement of data in memory plus the procedures that maintain it, for example a dynamic array or a hash table.
- Algorithm
- A finite sequence of well-defined steps that solves a problem for every valid input, for example binary search or merge sort.
- Abstract data type (ADT)
- A specification of what operations a type supports and how they behave, with no commitment to how they are implemented.
- Operation
- Something you do to a structure: insert, delete, look up, find the minimum, iterate in order.
- Complexity
- How the time or memory an algorithm uses grows as the input grows, usually written in Big-O Notation.
A good algorithm has three properties. It is correct (it produces the right answer for every valid input, including edge cases), it terminates, and it is efficient enough for the input sizes you actually face.
ADT vs implementation
An ADT is a contract; an implementation is one way to honor it. A map promises put, get and delete by key. A hash table and a balanced binary search tree both keep that promise, but with very different costs and guarantees. Separating the two lets you reason about what you need before deciding how to build it.
| ADT | Core operations | Common implementations | Trade-off |
|---|---|---|---|
| List / sequence | get(i), insert, remove | Dynamic array, linked list | Array: O(1) indexing. Linked list: O(1) splice at a known node. |
| Stack | push, pop, peek | Dynamic array, linked list | Both O(1); arrays win on cache locality. |
| Queue / deque | enqueue, dequeue | Circular buffer, linked list | Circular buffer avoids per-node allocation. |
| Map / dictionary | put, get, delete | Hash table, balanced BST | Hash: O(1) average, unordered. BST: O(log n), keys kept sorted. |
| Set | add, contains, remove | Hash set, tree set, bitset | Bitsets are tiny and fast when keys are small integers. |
| Priority queue | push, pop-min, peek-min | Binary heap | O(log n) push and pop, O(1) peek. |
A map of data structures
Almost every structure you will meet belongs to one of four families. Knowing the family tells you its strengths before you know the details.
| Family | Shape | Examples | Good at |
|---|---|---|---|
| Linear | Elements in a sequence, each with at most one successor | Arrays & Dynamic Arrays, Strings, Linked Lists, Stacks, Queues & Deques | Ordered traversal, position-based access, processing in arrival order |
| Hierarchical | Parent and child links, no cycles | Trees & Binary Trees, Binary Search Trees, Heaps & Priority Queues, Tries (Prefix Trees), B-Trees & B+ Trees | Sorted search in O(log n), priorities, prefixes, on-disk indexes |
| Graph | Arbitrary connections between vertices | Adjacency lists and matrices (Graph Fundamentals) | Networks, maps, dependencies, social connections |
| Hash-based | A hash function maps keys to buckets | Hash Tables, hash sets, Bloom filters | Membership and lookup by key in O(1) on average |
Some specialized structures combine ideas from several families: Segment Trees and Fenwick Trees (BIT) answer range queries, Union-Find (Disjoint Set) tracks connected groups, Skip Lists layer linked lists to get logarithmic search, and an LRU & LFU Cache pairs a hash map with a doubly linked list.
Algorithm paradigms
Structures describe how data sits; paradigms describe how algorithms attack problems. Most solutions are one of a handful of strategies, sometimes combined.
| Paradigm | Core idea | Classic examples |
|---|---|---|
| Brute force | Try every candidate and keep the best | Linear Search, checking all pairs, generating all subsets |
| Divide and conquer | Split into independent subproblems, solve recursively, combine | Merge Sort, Quick Sort, Binary Search |
| Greedy | Make the locally best choice and never revisit it | Dijkstra's Algorithm, Minimum Spanning Trees, interval scheduling |
| Dynamic programming | Solve overlapping subproblems once and reuse the answers | Knapsack Problems, LCS & Edit Distance, shortest paths in a DAG |
| Backtracking | Build a solution step by step and abandon dead ends early | N-Queens, Sudoku, permutations (Backtracking) |
| Graph search | Systematically explore states and transitions | Breadth-First Search, Depth-First Search, A* Pathfinding |
How to choose a data structure
- 1
List the operations
Write down what the code does repeatedly: look up by key, access by position, take the minimum, add at both ends, iterate in sorted order, query a range, match a prefix.
- 2
Estimate sizes and frequencies
How large is
n? How many queries? Reads vs writes? Input constraints tell you the target complexity (see Time & Space Complexity Analysis). - 3
Match operations to structures
Use the table below. The right structure makes the hottest operation cheap, even if rarer operations get slower.
- 4
Check extra requirements
Do you need ordering, duplicates, stable iteration order, bounded memory, persistence, or thread safety?
- 5
Start simple, then measure
Pick the simplest structure that meets the target. Optimize only when the numbers say you must.
| If you need to... | Reach for | Typical cost |
|---|---|---|
| Access elements by index | Array or dynamic array | O(1) |
| Test membership or look up by key | Hash set or hash map | O(1) average |
| Keep keys sorted, find floor/ceiling, iterate a range | Balanced BST (TreeMap, std::map) | O(log n) |
| Repeatedly take the smallest or largest item | Heap / priority queue | O(log n) push and pop |
| Add and remove at both ends | Deque | O(1) |
| Undo, match brackets, process most recent first | Stack | O(1) |
| Process items in arrival order | Queue | O(1) |
| Search by string prefix | Trie | O(L) for a key of length L |
| Merge groups and ask "same group?" | Union-find | Nearly O(1) amortized |
| Range sums with point updates | Fenwick tree or segment tree | O(log n) |
Worked example: list scan vs set lookup
You have n numbers and must answer q questions of the form "is x in the collection?". The data never changes between questions. Two programs give identical answers, but they organize the data differently.
Scan a list every time
- No preprocessing
- Each query checks up to
nelements: O(n) - Total O(n · q)
- n = q = 10⁵ means about 10¹⁰ comparisons
Build a hash set once
- O(n) to insert everything
- Each query hashes
xand checks one bucket: O(1) average - Total O(n + q)
- n = q = 10⁵ means about 2 × 10⁵ operations
List scan
~10¹⁰ ops
Minutes in Python, seconds in C++
Hash set
~2 × 10⁵ ops
Well under a millisecond in C++
Speedup
~50,000×
Same answers, different structure
How to study DSA effectively
- Learn in layers. First the structure and its invariants, then the cost of each operation, then the problem patterns built on it.
- Practice by pattern. Solve 3 to 5 problems of one pattern (say Sliding Window) back to back so the shape sticks, then mix patterns so you learn to recognize them.
- Trace by hand. Draw the array, the pointers, the tree. The visualizations on this site exist so you can watch state change step by step.
- Time-box. Give a problem 25 to 40 minutes. If stuck, study a solution until you can explain why it works, then re-solve it from scratch a few days later.
- Always state complexity. Write the time and space bound for every solution you finish and justify it in one sentence.
- Implement the core structures once. Building a hash map or heap yourself makes their costs intuitive forever.
- 1
Understand
Restate the problem, write two or three small examples, and list edge cases (empty input, duplicates, negatives, huge values).
- 2
Brute force
Describe the simplest correct solution and its complexity. It is your safety net and your baseline.
- 3
Find the bottleneck
Which operation is repeated the most? That is the one a better structure or pattern must speed up.
- 4
Optimize
Apply the structure or pattern that removes the bottleneck: a hash map for repeated lookups, sorting plus two pointers, a heap for repeated minimums.
- 5
Code and test
Write clean code, then walk through your examples and edge cases by hand before running anything.
A tour of this site
Why this matters beyond interviews
- Databases index rows with B-Trees & B+ Trees so a lookup touches a handful of disk pages instead of millions.
- Network routers match IP prefixes with trie-like structures, and maps apps route you with Dijkstra's Algorithm and A* Pathfinding.
- Compilers parse expressions with Stacks, and every function call you make lives on the call stack.
- Caches in browsers, CDNs and databases are hash maps with an eviction policy such as LRU.
- Version control computes diffs with the same dynamic programming that powers LCS & Edit Distance.
Complexity
| Approach | Preprocessing | Per query | Total for q queries | Extra space |
|---|---|---|---|---|
| Scan an unsorted list | O(1) | O(n) | O(n · q) | O(1) |
| Sort + binary search | O(n log n) | O(log n) | O((n + q) log n) | O(1) to O(n) |
| Hash set | O(n) | O(1) average | O(n + q) | O(n) |
Membership queries on a static collection of n items. The hash set's O(1) is an average; a pathological hash function can degrade it to O(n).
Implementation
Counts how many queries appear in the data, first with a linear scan per query, then with a hash set built once. Run it and compare the timings.
import random
import time
def count_hits_scan(data: list[int], queries: list[int]) -> int:
hits = 0
for q in queries: # q iterations
if q in data: # list membership is a linear scan: O(n)
hits += 1
return hits # total O(n * q)
def count_hits_set(data: list[int], queries: list[int]) -> int:
seen = set(data) # build once: O(n)
hits = 0
for q in queries:
if q in seen: # hash lookup: O(1) on average
hits += 1
return hits # total O(n + q)
if __name__ == "__main__":
n = 20_000
data = [random.randrange(10 * n) for _ in range(n)]
queries = [random.randrange(10 * n) for _ in range(n)]
for fn in (count_hits_scan, count_hits_set):
start = time.perf_counter()
hits = fn(data, queries)
elapsed = time.perf_counter() - start
print(f"{fn.__name__}: {hits} hits in {elapsed:.3f}s")Key takeaways
- A data structure organizes data so specific operations are cheap; an algorithm is a correct, terminating, efficient procedure over that data.
- Separate the ADT (what operations you need) from the implementation (how they are provided and at what cost).
- Most structures fall into four families: linear, hierarchical, graph and hash-based. Most algorithms follow a few paradigms: brute force, divide and conquer, greedy, dynamic programming, backtracking and graph search.
- Choose a structure by listing your operations, estimating sizes, and making the most frequent operation cheap.
- Swapping a list scan for a hash set turns O(n · q) into O(n + q) with identical answers.
- Study by pattern, trace by hand, state complexity for every solution, and re-solve problems after a delay.
Common pitfalls
- Jumping to code before listing the operations the problem actually needs.
- Memorizing solutions instead of the patterns behind them, which fails as soon as a problem is reworded.
- Treating hash-based O(1) as unconditional: it is an average that depends on a good hash function and load factor.
- Picking a fancy structure when a sorted array or plain hash map would do; simpler code has fewer bugs.
- Ignoring constraints: the input size usually tells you which complexity, and therefore which technique, is expected.
Interview tips
- Name the ADT first ("I need fast lookup by value"), then the implementation and its cost ("a hash map, O(1) average").
- Always present a brute force with its complexity before optimizing; it proves you understand the problem.
- When you optimize, say which operation was the bottleneck and how the new structure removes it.
Real-world applications
- Database indexes (B-trees, hash indexes) that turn full-table scans into a few page reads.
- Autocomplete with tries, spell checkers with hash sets, and routing with graphs.
- Schedulers and event simulators built on priority queues.
- Caches (LRU and LFU) combining hash maps with linked lists.
Practice problems
Test yourself
Which of these is an abstract data type rather than an implementation?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.