How to Learn Data Structures and Algorithms: A Roadmap That Starts With Patterns
The usual way to learn algorithms is to solve problems until patterns appear on their own. It works, and it is slow. Learn the patterns on purpose and most problems turn out to be one of about a dozen ideas in disguise.
Ask how to get good at algorithms and the usual answer is a number: solve 300 problems, or 500. People who followed that advice will tell you it worked. What they tend to leave out is that somewhere along the way they stopped seeing problems and started seeing patterns: this one is a sliding window, that one is a breadth-first search wearing a costume. The problems were never the point. The patterns were, and you can learn those directly.
This roadmap is ordered that way. Each stage adds one or two tools, the signal in a problem statement that tells you to reach for them, and a test for whether you are ready to move on. Every stage links to the matching lessons in our own algorithms and data structures course, which covers the same ground in a slightly different order, but the roadmap works with any textbook or problem site.
The short version
If you read only one section, read this one. Learn these eight things, in this order:
- Counting steps. Big-O notation, and the habit of estimating whether an idea is fast enough before you write it.
- Arrays and hash tables. The two structures behind most everyday code and a large share of interview answers.
- The array patterns. Two pointers, sliding windows, prefix sums and binary search.
- Stacks and queues. Including the monotonic stack, which looks like a trick until you have seen it three times.
- Recursion and trees. Learning to trust a function that calls itself.
- Graphs. Breadth-first and depth-first search first, shortest paths after.
- Dynamic programming. Recursion that remembers its answers.
- Greedy algorithms and backtracking. And then the part that takes longest: telling which tool a problem wants.
Everything past that, from segment trees to network flow, is built from these eight and can wait until you need it.
How much math do you need?
Less than the textbooks suggest. You need logarithms (how many times can you halve a million? About twenty), the fact that is roughly , and enough comfort with induction to believe that a recursive function works if it works on smaller inputs. That covers all eight stages.
Proofs matter more later. Greedy algorithms in particular are easy to invent and easy to get wrong, and the only protection is being able to argue why a greedy choice is safe. You can pick that up when you get there. The general tools are in Correctness: Invariants & Proofs, and the arguments that greedy algorithms need are in Proving Greedy Algorithms Correct.
Stage 1: learn to count steps
Before any data structure, learn to answer one question: if the input has items, roughly how many steps does this take? That is all Big-O notation is. It is the most useful skill on this list, because it lets you reject a slow idea before you spend an hour coding it.
A rule of thumb worth memorizing: a compiled language gets through something like simple operations a second, and Python is often 10 to 100 times slower. So if a problem says can be 100,000, a solution that compares every pair of items needs about steps and is hopeless, while one that sorts first needs a couple of million and finishes at once. The limits on the input tell you what kind of algorithm a problem expects before you have had a single idea.
You are done with this stage when you can look at two nested loops, or a loop that halves its range each time, and state the running time without counting on your fingers.
Stage 2: arrays and hash tables
Most real programs, and most interview problems, are solved with two structures. An array gives you any element by position in constant time. A hash table gives you any element by key in constant time on average. You already use them: a Python dict or set, a Java HashMap, a C++ unordered_map.
One of the most common speed-ups in problem solving is replacing a search through a list with a lookup in a hash table. “Have I seen this value before?” asked inside a loop is a full scan each time, so overall. Keep a set of what you have seen and the same loop is . If you take one trick from this article, take the habit of noticing that question.
You are done when you can explain why appending to a dynamic array is cheap on average even though it sometimes copies everything, and when a hash table lookup is not constant time.
Stage 3: the four array patterns
This is where the roadmap differs most from a textbook’s table of contents. Four techniques turn a slow double loop over an array into a single pass or a handful of halvings, and they come up constantly.
- Two pointers. Two indices move through a sorted array, usually toward each other. Signal: sorted input and a question about pairs.
- Sliding window. Keep a running answer for a contiguous stretch, add one element on the right and drop one on the left. Signal: “the longest (or shortest) subarray or substring such that…”.
- Prefix sums. Compute the running total once, then get the sum of any range with one subtraction. Signal: many questions about ranges of the same array.
- Binary search. Halve the possibilities at every step. The obvious use is finding a value in sorted data. The less obvious one is searching over answers: if you can quickly check “is 37 enough?”, and enough stays enough as the number grows, you can binary search for the smallest number that works.
Here is the first one, small enough to hold in your head. Does a sorted list contain two numbers that add up to a target?
def has_pair_with_sum(a, target):
"""a is sorted, smallest first."""
lo, hi = 0, len(a) - 1
while lo < hi:
s = a[lo] + a[hi]
if s == target:
return True
if s < target:
lo += 1 # need a bigger sum
else:
hi -= 1 # need a smaller sum
return False
nums = [1, 3, 4, 6, 9, 11]
print(has_pair_with_sum(nums, 13))
# True, because 4 + 9 = 13One pass instead of checking every pair: instead of .
Don’t memorize the code. Memorize why moving lo is safe: if the smallest remaining number plus the largest is still too small, the smallest number can’t be part of any answer, so it can be thrown away for good. Every pattern on this list has a sentence like that underneath it, and the sentence is what carries over to the next problem.
You are done when you can read a new array problem and say which of the four fits, and why, before you write any code.
Stage 4: stacks, queues and the monotonic stack
A stack hands back the most recent thing you put in. A queue hands back the oldest. That is the whole definition, and between them they run undo histories, bracket matching, expression evaluation, and both of the graph searches in stage 6.
Then learn one specific technique, the monotonic stack: a stack you keep in sorted order by throwing away elements that can never matter again. It answers “for each element, where is the next larger one?” for a whole array in a single pass, and a family of problems that look unrelated (daily temperatures, stock spans, the largest rectangle in a histogram) all reduce to it.
Linked lists belong here too. They matter less in practice than their share of interview questions suggests, but they are the gentlest introduction to pointers, and trees are built from the same parts.
You are done when you can explain why each element is pushed and popped at most once in a monotonic stack, which is why the whole pass takes linear time.
Stage 5: recursion and trees
Recursion is the first real wall for most people, and the way through is to stop simulating it. You can’t trace five levels of calls in your head, and you don’t need to. Assume the function already works on anything smaller, use that to solve the current case, and check the smallest case by hand. That leap of faith is what takes practice.
Binary trees are where it pays off. Nearly every tree question has the same shape: get an answer from the left subtree, get one from the right, combine them. The height of a tree is one more than the larger of its children’s heights, and that sentence is also the code.
Add heaps while you are here. A heap keeps the smallest (or largest) item one step away at all times, and it is the answer whenever a problem says “the largest” or “repeatedly take the best one”.
You are done when you can write the height, the size and an in-order traversal of a binary tree without looking anything up.
Stage 6: graphs
A graph is things and the connections between them: cities and roads, courses and prerequisites, the cells of a grid and their neighbors. Plenty of problems that never use the word are graph problems, and noticing that is half the work.
Start with the two ways to explore one. Breadth-first search and depth-first search are the same loop with a different structure holding the to-do list: a queue for BFS, a stack for DFS. BFS finds the route with the fewest steps. DFS is the tool for cycles, dependencies and anything that needs an ordering. We compare the two in detail in BFS vs DFS.
After that come topological sort for dependencies, Dijkstra’s algorithm for shortest paths when roads have different lengths, and union-find for questions about what is connected to what.
You are done when you can take a maze drawn on a grid, say what the nodes and edges are, and find the shortest way out.
Stage 7: dynamic programming
Dynamic programming has a reputation it doesn’t deserve. It is recursion plus a notebook: if a recursive function keeps being asked the same question, write the answer down the first time and look it up after that. A recursion that took exponential time often drops to polynomial time with a few added lines.
The notebook is never the hard part. The hard part is deciding what the subproblems are: what a function needs to know, and nothing more, to finish the job from here. So start with From Recursion to Dynamic Programming, write the slow recursive solution first every single time, and only then add the memory. The classic problems (longest common subsequence and edit distance, knapsack and coin change) are worth doing in that order, because each teaches a different shape of subproblem.
You are done when you can take a problem that asks “how many ways” or “the cheapest way”, define the subproblem in one sentence, and say how many subproblems there are.
Stage 8: greedy, backtracking and choosing the tool
Two more ideas round out the everyday toolkit. A greedy algorithm takes the best-looking option at each step and never reconsiders. When it works it is the simplest and fastest solution there is. When it doesn’t, it gives wrong answers that look right, which is why a greedy solution needs an argument and not just a passing example. Backtracking has the opposite temperament: make a choice, follow it as far as it goes, undo it and try the next. It is how you list permutations, solve a Sudoku or place eight queens.
By this point the hard part is choosing, and the clues are usually in the wording.
| What the problem says | What to try first |
|---|---|
| A sorted array and a question about pairs | Two pointers |
| The longest or shortest contiguous stretch with some property | Sliding window |
| Many sums over ranges of the same array | Prefix sums |
| “The smallest value that is enough”, and a value is quick to test | Binary search on the answer |
| For each element, the next larger or smaller one | Monotonic stack |
| “Have I seen this before?”, or counting occurrences | Hash table |
| The largest, or repeatedly taking the best item | Heap |
| The fewest steps or moves | Breadth-first search |
| Prerequisites, dependencies or a required order | Topological sort |
| Count the ways, or the best total over a sequence of choices | Dynamic programming |
| Every arrangement, or a puzzle solved by trying options | Backtracking |
Our course spends a whole lesson on this step: Recognizing the Right Technique.
How long does it take?
| Goal | What it means | Realistic time |
|---|---|---|
| The core toolkit | Stages 1 to 4: you can estimate running time and solve common array, string and hash table problems | 4 to 8 weeks at about an hour a day |
| Interview ready | All eight stages, with enough practice to spot the pattern in a problem you have not seen | 3 to 6 months, part-time |
| Contest depth | Advanced structures and techniques, used under time pressure | A year or more of regular practice |
These are honest ranges, not promises, and they assume you already write code comfortably in one language. The number that matters is not problems solved. Fifty problems you could solve again from a blank page next month are worth more than three hundred you once got accepted.
Five mistakes that cost people months
- Solving problems in random order. A random problem tests a random technique, usually one you haven’t met. Work through one pattern until it is boring, then move on.
- Reading the solution too early, or far too late. Give a problem an honest half hour. If you are still stuck, read the idea (not the code), close the page, and write the solution yourself. Staring at a problem for three hours teaches less than people hope.
- Memorizing code. Binary search is half a dozen lines and famously easy to get wrong by one. The cure is knowing the invariant, the thing that is true about
loandhievery time around the loop, and deriving the code from it. - Skipping the analysis. If you can’t say how fast your solution is, you can’t know whether to keep it. Say the running time out loud before you run anything.
- Never coming back. A solution you worked out once and never revisited fades fast. Solve the problem again a few days later, then a few weeks later. We wrote about why that works in Why You Forget What You Learn.
Which language should you use?
The one you already know. The ideas are identical in Python, Java, C++ and JavaScript, and most interviews let you choose. Python has the least ceremony, which is why most of the code in our lessons is Python. C++ is the standard in competitive programming because of its speed. Switching languages in order to learn algorithms is solving the wrong problem.
Common questions
Is DSA hard to learn?
The first four stages are not. They are careful bookkeeping, and most people are surprised how quickly array problems start to feel routine. Recursion and dynamic programming are where it gets hard for nearly everyone, and what gets people through is repetition: the tenth recursive function is far easier to write than the second.
Should I learn data structures or algorithms first?
Together. A data structure is only interesting because of the operations it makes fast, and an algorithm is usually only fast because of the structure it keeps its data in. Heaps and heapsort, hash tables and duplicate detection, queues and breadth-first search: each pair is really one idea.
How many problems do I need to solve?
Fewer than you think, if you choose them. As a rough guide, ten to fifteen per pattern, spread out and revisited, builds more skill than a few hundred picked at random. When a new problem makes you think “this is like that other one”, the pattern has landed.
Do I still need this if AI tools can write the code?
More than before, in one specific way. A coding assistant will happily produce a solution that is correct on small inputs and takes an hour on real ones, or one that breaks on an empty list. Someone has to notice. Knowing what a good solution looks like, how fast it should be and where it is likely to fail is exactly what studying algorithms gives you.
Can I learn data structures and algorithms for free?
Yes. There are excellent free university lecture series and textbooks, and the big problem sites have free tiers. Our own algorithms and data structures course is free too: 190 lessons in three levels of depth, with 30 live simulations, most of which let you step through an algorithm and watch the data structure change.