Skip to the content.

How to Master Data Structures and Algorithms: The Complete 2027 Roadmap

A staged, free-first path to mastering data structures and algorithms (DSA) — from Big-O basics to graphs, dynamic programming and interview-ready problem solving, with tested Python reference code.

If you want to learn data structures and algorithms properly — for coding interviews, competitive programming, or simply to write faster, cleaner software — this guide gives you an order to learn things in, honest time estimates, the best free books and courses, practice sets, and a small library of readable implementations you can run and break.

Last reviewed: December 2026


Table of contents


Who this is for

You need basic programming in one language: variables, loops, functions, and lists. Nothing else.

How to use this roadmap

  1. Go through the stages in order. Each one assumes the previous ones.
  2. For every structure: read the idea, implement it yourself from memory, solve 5–15 problems that use it.
  3. Do not just watch videos. The skill is built by struggling with problems for 20–40 minutes before reading a solution.
  4. Keep a notebook (or a markdown file) of every problem you failed: what the trick was, and what clue should have led you there. Re-solve them a week later.

The roadmap at a glance

Stage Topic Time (at ~8–10 h/week) You’re done when you can…
0 Language + setup 2–5 days write and run small programs, use built-in lists/maps
1 Big-O, memory model 1 week state the time and space cost of any loop you write
2 Arrays, strings, linked lists, stacks, queues 2 weeks reverse a linked list and implement a queue from two stacks
3 Hash maps and sets 1 week explain collisions and solve “two sum” style problems in O(n)
4 Recursion, sorting, binary search 2 weeks write merge sort and a bug-free binary search
5 Trees, BSTs, heaps, tries 2–3 weeks traverse trees iteratively and use a heap for top-k
6 Graphs: BFS, DFS, shortest paths, topological sort 3 weeks model a problem as a graph and pick the right traversal
7 Greedy and dynamic programming 3–4 weeks define a DP state and transition on your own
8 Union-find, segment/Fenwick trees, advanced 2+ weeks answer range queries in O(log n)
9 Interview patterns + timed practice ongoing solve most medium problems in ~30 minutes

Total: roughly 4–6 months part-time for solid interview-level mastery; 6–12 weeks if you already know some of it and study full-time.

Stage 0: Pick a language and set up

Best pick: Python for learning and interviews — the syntax stays out of your way, and list, dict, set, collections.deque and heapq cover most needs. C++ is the best pick for competitive programming because of speed and the STL. Java is a solid choice if it’s your work language.

Language Pros for DSA Cons Key references
Python short code, rich standard library slower; recursion depth limit (~1000 by default) collections, heapq, bisect, TimeComplexity wiki
C++ fastest, STL containers, standard in contests more verbose, undefined behavior pitfalls cppreference containers
Java strong typed collections, common in industry verbose java.util package
JavaScript/TypeScript great if you’re a web dev no built-in heap or ordered map MDN Map
Rust safe and fast borrow checker makes linked structures hard to learn on std::collections

Setup: any editor plus a terminal is enough. Use Python Tutor to step through code visually when pointers and recursion get confusing.

Stage 1: Complexity and the mental model

Learn to answer two questions about any code: how does running time grow with input size, and how much extra memory does it use.

Core ideas:

Rules of thumb for a ~1 second limit (useful in contests and for sanity checks):

n up to Acceptable complexity
~10 O(n!)
~20 O(2ⁿ)
~500 O(n³)
~5,000 O(n²)
~10⁶ O(n log n)
~10⁸ O(n) in a fast language

These are rough, language-dependent guides, not laws.

Exercise: for 10 snippets of your own old code, write down time and space complexity, then check by timing with n = 10³, 10⁴, 10⁵.

Read: chapter 1 of Jeff Erickson’s free Algorithms (see Best books) and the “Analysis of Algorithms” section of the Algorithms, 4th Edition booksite.

Stage 2: Linear structures

Structure Key operations Learn to implement Typical problems
Static/dynamic array index O(1), append amortized O(1), insert middle O(n) resizing array prefix sums, rotate array, two pointers
String like arrays; often immutable — palindromes, anagrams, substring search
Singly/doubly linked list insert/delete at known node O(1), search O(n) singly list with head/tail reverse list, detect cycle, merge two sorted lists
Stack (LIFO) push/pop O(1) on top of an array valid parentheses, monotonic stack, undo
Queue (FIFO) / deque enqueue/dequeue O(1) two-stack queue, ring buffer BFS, sliding window maximum

Techniques to master here: two pointers, sliding window, prefix sums, fast/slow pointers (Floyd’s cycle detection), monotonic stack.

Implementations: see DynamicArray, LinkedList, Stack, Queue in code/structures.py.

Stage 3: Hashing

Hash tables are the most useful structure in day-to-day programming.

Problems to drill: two sum, group anagrams, longest consecutive sequence, subarray sum equals k (prefix sum + hash map), LRU cache.

Implementation: HashMap (separate chaining with rehash) and LRUCache in code/structures.py.

Stage 4: Recursion, sorting and searching

Recursion: base case, recursive case, trust the function. Draw the call tree. Learn how memoization turns exponential trees into polynomial ones (this is the bridge to DP).

Sorting — know these cold:

Algorithm Time (avg / worst) Space Stable Why learn it
Insertion sort O(n²) / O(n²) O(1) yes fast for tiny/nearly-sorted inputs
Merge sort O(n log n) / O(n log n) O(n) yes divide and conquer, counting inversions
Quicksort O(n log n) / O(n²) O(log n) no partitioning, quickselect
Heapsort O(n log n) / O(n log n) O(1) no heaps in action
Counting/radix sort O(n + k) O(n + k) yes beating n log n with bounded keys

Python’s built-in sort is Timsort (stable, O(n log n)); in practice use it, but understand the others.

Binary search is deceptively hard to write correctly. Learn one template and stick to it, then learn binary search on the answer (e.g., “minimum capacity to ship packages in D days”).

Backtracking: subsets, permutations, combination sum, N-Queens, word search.

Stage 5: Trees and heaps

Problems: max depth, validate BST, lowest common ancestor, serialize/deserialize tree, kth largest element, top-k frequent, implement trie, word search II.

Implementations: BST, MinHeap, Trie in code/structures.py.

Stage 6: Graphs

Graphs are where DSA starts to feel powerful: maps, networks, dependencies, grids and states are all graphs.

Topic Algorithm Complexity Use when
Representation adjacency list vs matrix O(V+E) vs O(V²) space lists for sparse graphs (almost always)
Traversal BFS O(V+E) shortest path in unweighted graphs, levels
Traversal DFS O(V+E) connectivity, cycles, backtracking on grids
Ordering topological sort (Kahn / DFS) O(V+E) dependencies, course schedule
Shortest path Dijkstra O((V+E) log V) non-negative weights
Shortest path Bellman–Ford O(VE) negative edges, detect negative cycles
Shortest path Floyd–Warshall O(V³) all pairs, small V
Shortest path 0-1 BFS O(V+E) weights only 0 or 1
MST Kruskal (with union-find) / Prim O(E log E) cheapest network connecting all nodes
Components union-find ~O(α(n)) per op dynamic connectivity
Advanced SCC (Tarjan/Kosaraju), bridges, max flow varies contests, harder interviews

Great free explainers: cp-algorithms Dijkstra and Red Blob Games’ interactive introduction to A*.

Implementations: bfs_shortest_path, dijkstra, topological_sort, UnionFind in code/structures.py.

Stage 7: Greedy and dynamic programming

Greedy: make the locally best choice and prove it can’t hurt (exchange argument). Classic: interval scheduling, jump game, Huffman coding, gas station.

Dynamic programming is the hardest stage for most people. A repeatable method:

  1. Write a brute-force recursive solution.
  2. Identify the state — the minimal parameters that describe a subproblem.
  3. Write the transition — how a state is built from smaller states.
  4. Add memoization (top-down) — usually enough to pass.
  5. Convert to a table (bottom-up) and optimize space if needed.

DP families to learn, in order:

Family Examples
1D climbing stairs, house robber, decode ways
2D grid unique paths, minimum path sum
Knapsack 0/1 knapsack, partition equal subset sum, coin change
Sequences longest increasing subsequence, longest common subsequence, edit distance
Intervals burst balloons, matrix chain multiplication
Trees house robber III, tree diameter
Bitmask travelling salesman for small n
Digit / probability contest-level topics

Stage 8: Advanced structures

Learn these after the basics feel automatic:

Stage 9: Patterns for interviews

Most interview problems are variations on a small set of patterns. Learn to recognize the clue:

Pattern Clue in the problem Typical structure
Two pointers sorted array, pairs, in-place array
Sliding window “longest/shortest substring/subarray with…” hash map + two indices
Prefix sums “sum of subarray”, many range queries array + hash map
Binary search sorted input, or “minimum value such that…” array
Fast/slow pointers cycle, middle of list linked list
Monotonic stack “next greater element”, histogram stack
BFS shortest steps, levels, grid flood queue
DFS / backtracking all combinations, paths recursion
Topological sort prerequisites, ordering graph + indegree
Union-find connected groups, merging accounts DSU
Heap top-k, k-way merge, running median priority queue
Intervals overlapping meetings sort + sweep
Trie prefixes, word dictionary trie
DP “number of ways”, “min/max cost”, choices at each step table
Bit manipulation “single number”, subsets integers

Popular curated lists: the free NeetCode roadmap, Grind 75 from the Tech Interview Handbook, Sean Prashad’s LeetCode Patterns, and LeetCode’s Top Interview 150.

How to practice a problem (the 40-minute loop):

  1. Restate the problem and write 2–3 examples, including edge cases.
  2. Say the brute force and its complexity out loud.
  3. Find the bottleneck; look for the pattern.
  4. Code it cleanly; test it by hand on your examples.
  5. If stuck after ~30–40 minutes, read the solution, then close it and write it yourself.
  6. Log it. Re-solve in 3 days and again in 2 weeks.

Choosing a data structure: cheat table

You need to… Use
access by index array / list
look up by key, count, dedupe hash map / hash set
keep items sorted with fast insert balanced BST (e.g., TreeMap in Java, std::map in C++), or a sorted list + bisect for small data
get min/max repeatedly heap
process in arrival order queue / deque
undo, matching brackets, DFS stack
prefix search trie
merge groups / check connectivity union-find
range sums with updates Fenwick tree or segment tree
model relationships graph (adjacency list)
evict least-recently-used hash map + doubly linked list (OrderedDict)

Big-O reference table

Structure Access Search Insert Delete Notes
Array (dynamic) O(1) O(n) O(1)* end / O(n) middle O(1) end / O(n) middle *amortized
Linked list O(n) O(n) O(1) at known node O(1) at known node  
Stack / queue — O(n) O(1) O(1)  
Hash table — O(1) avg O(1) avg O(1) avg O(n) worst
BST (balanced) — O(log n) O(log n) O(log n) unbalanced: O(n)
Binary heap O(1) min O(n) O(log n) O(log n) pop heapify O(n)
Trie — O(L) O(L) O(L) L = key length
Union-find — ~O(1) ~O(1) — amortized, inverse Ackermann
Fenwick / segment tree — O(log n) query O(log n) update —  

A printable overview lives at the Big-O Cheat Sheet.

Best books

Free and legal (author or publisher hosted):

Book Author(s) Best for Link
Algorithms Jeff Erickson rigorous but readable; recursion, DP, graphs free from the author
Open Data Structures Pat Morin implementing structures from scratch (open license) opendatastructures.org
Competitive Programmer’s Handbook Antti Laaksonen concise contest-oriented coverage author’s page
Think Data Structures Allen B. Downey Java-based, practical Green Tea Press
Problem Solving with Algorithms and Data Structures using Python Brad Miller, David Ranum et al. gentle Python intro, interactive Runestone Academy
Hello Algo community (krahets) illustrated, multi-language, beginner-friendly hello-algo.com / GitHub
Mathematics for Computer Science Lehman, Leighton, Meyer proofs, counting, probability for algorithms MIT PDF

Paid (worth buying):

Book Why Link
Introduction to Algorithms (CLRS), 4th ed. — paid the standard reference; dense, best as a reference not a first read MIT Press
Algorithms, 4th ed. (Sedgewick & Wayne) — paid; booksite free clear Java implementations, great visuals booksite
The Algorithm Design Manual (Skiena) — paid practical “war stories” and a catalog of problems algorist.com
Grokking Algorithms, 2nd ed. (Bhargava) — paid friendliest illustrated intro Manning
Algorithm Design (Kleinberg & Tardos) — paid greedy, DP, flows; strong on problem modeling Pearson
Cracking the Coding Interview — paid interview classic official site
Beyond Cracking the Coding Interview — paid newer, pattern- and process-focused official site
Elements of Programming Interviews — paid harder problems, Python/Java/C++ editions official site

Best pick: start with Grokking Algorithms (or free Hello Algo) for intuition, then work through Erickson or Sedgewick for depth. Keep CLRS as a reference.

Best courses and video lectures

Course Cost Level Why
MIT 6.006 Introduction to Algorithms (Spring 2020) free intermediate the best free university course; lectures, notes, problem sets
MIT 6.046J Design and Analysis of Algorithms free advanced follow-up to 6.006
Princeton Algorithms Part I / Part II (Coursera) free to enroll intermediate Java, excellent assignments with autograder
Stanford Algorithms Specialization (Coursera) audit free; certificate paid intermediate–advanced proof-oriented, language-agnostic
UC San Diego Data Structures and Algorithms Specialization (Coursera) audit free; certificate paid beginner–advanced many programming assignments
CS50x (Harvard) free beginner if you need programming fundamentals first
Berkeley CS 61B free materials beginner–intermediate data structures in Java with great projects
Khan Academy Algorithms free beginner gentle intro to sorting, recursion, graphs
NeetCode roadmap and videos free; Pro paid interview problem walkthroughs organized by pattern

YouTube channels:

Best pick: MIT 6.006 for understanding + NeetCode roadmap for practice is the strongest free combination.

Practice platforms compared

Platform Cost Best for Notes
LeetCode free; Premium paid interviews huge problem set, company tags behind Premium
NeetCode practice free lists structured interview prep links to LeetCode problems
CSES Problem Set free classic algorithm training ~300 carefully chosen problems
Codeforces free contests, rating frequent rated rounds
AtCoder free clean contests Beginner Contests are ideal to start
USACO Guide free structured CP curriculum Bronze → Platinum modules
Kattis free ICPC-style problems  
CodeChef free contests, beginners  
HackerRank free warm-up, company screens many company tests use it
Exercism free language fluency, mentoring not DSA-focused but great for fundamentals
Project Euler free math + algorithms  
Advent of Code free fun yearly puzzles heavy on graphs, simulation, parsing

Best pick: LeetCode (free tier) for interviews; CSES + AtCoder for building real algorithmic strength.

Visualizers and tools

Open-source implementation collections worth reading:

The code in this repo

code/structures.py contains small, commented reference implementations (Python 3, standard library only):

Name What it shows
DynamicArray doubling/halving capacity, amortized O(1) append
LinkedList head/tail pointers, remove, in-place reverse
Stack, Queue LIFO on a list; FIFO from two stacks
HashMap separate chaining, load factor, rehashing
MinHeap sift up/down, O(n) heapify
BST insert, search, delete with successor, iterative inorder
Trie insert, search, prefix check
UnionFind path compression + union by size
FenwickTree prefix and range sums with point updates
LRUCache O(1) get/put with OrderedDict
bfs_shortest_path, dijkstra, topological_sort, binary_search core algorithms

Run the tests (14 tests, including randomized checks against built-ins):

python3 -m unittest discover -s code -v

How to use it: read one class, close the file, rewrite it from memory in your own file, then run the tests against your version (change the import). That rewrite-from-memory step is where learning happens.

Projects and exercises

Small projects that force you to use DSA for real:

  1. Autocomplete CLI — load a word list into a trie, rank suggestions by frequency with a heap.
  2. Maze solver — generate a maze (randomized DFS or Kruskal with union-find), solve it with BFS and A*, print the path.
  3. Mini spreadsheet — cells with formulas; detect cycles and evaluate in topological order.
  4. LRU-cached HTTP fetcher — implement the cache yourself with a hash map + doubly linked list.
  5. Text diff tool — longest common subsequence / edit distance to show line diffs.
  6. Route planner — load a small road graph (CSV), run Dijkstra, compare with BFS on hop count.
  7. Rate limiter — sliding window with a deque; token bucket.
  8. Leaderboard — top-k with a heap; then rank queries with a Fenwick tree.
  9. Benchmark notebook — time your sorts vs the built-in on random, sorted, and reversed data; plot the curves.
  10. Contest simulation — do one AtCoder Beginner Contest a week for 8 weeks; upsolve every problem you missed.

Study plans: 6 weeks, 12 weeks, 6 months

6-week interview sprint (~15 h/week, some prior knowledge):

Week Focus Problems
1 arrays, hashing, two pointers, sliding window 25
2 stacks, binary search, linked lists 25
3 trees, tries, heaps 25
4 graphs, backtracking 25
5 DP, greedy, intervals 25
6 mixed timed sets, mock interviews, re-solve failures 30

12-week foundation (~8–10 h/week, beginner): Stages 0–7 at the pace in the roadmap table, ~5 problems per week rising to ~12.

6-month mastery: 12-week foundation, then Stage 8, MIT 6.006 problem sets, the CSES Problem Set’s sorting/searching, DP and graph sections, and weekly contests.

Common mistakes

FAQ

How long does it take to learn data structures and algorithms? For interview readiness, most people need 3–6 months part-time. Deep mastery (contest level, advanced structures) takes years of regular practice.

Which language is best for DSA? Python for learning and interviews; C++ for competitive programming. The concepts transfer, so pick one and stay with it.

Do I need math? Basic algebra, logarithms, and some discrete math (induction, counting) help. Mathematics for Computer Science (free, linked above) covers everything you need.

How many LeetCode problems should I solve? There is no magic number. Many people feel ready after 150–300 well-understood problems covering all the patterns above.

Is DSA still worth learning with AI coding assistants? Yes. Assistants write code fast, but you still have to judge whether it’s correct and efficient, choose the right structure, and pass interviews that test reasoning live. Use AI to explain solutions after you attempt a problem, not instead of attempting it.

Should I learn data structures or algorithms first? Together. Each structure exists to make certain algorithms fast; this roadmap interleaves them.

Do I need to implement red-black trees? Rarely. Understand what balancing guarantees and use your language’s built-in ordered map.

What’s the difference between DSA for interviews and competitive programming? Interviews focus on common patterns, clear communication and clean code in ~45 minutes. Competitive programming goes deeper into math, advanced structures and speed under strict time limits.

Is GeeksforGeeks good? GeeksforGeeks has a huge number of articles; quality varies. Cross-check with cp-algorithms or a textbook for anything subtle.

Where to go next

Contributing

Found a broken link, a mistake in a complexity, or a great free resource that’s missing? Open an issue or a pull request. For code, keep implementations small, standard-library only, and add a test in code/test_structures.py. Please only add legally free resources and mark paid ones as paid.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.