Data Structures and Algorithms
A free DSA course for beginners, ordered so each topic builds on the last. Start with complexity and the core structures: arrays, linked lists, stacks, queues, trees and graphs. Each lesson shows how the data is laid out, how each operation works, and what it costs.
The DSA syllabus below runs in teaching order, so it doubles as a DSA roadmap. Sorting shows how order is created, searching how ordered data lets a program skip work, and the later sections cover recursion, greedy choices, dynamic programming and graph algorithms.
Start with the foundations
Learn how to describe an operation, estimate its running time, and choose storage that matches the work a program performs.
- Big O Notationlesson
The formal definition, why constants drop, and how to read the growth of code.
- Time and Space Complexitylesson
Compare constant, logarithmic, linear, and quadratic growth before choosing an implementation.
- Amortized Analysislesson
Why a rare expensive step still averages to O(1): the aggregate, accounting and potential methods.
- Recurrence Relationslesson
Write a recurrence for a recursive algorithm and solve it by substitution, recursion tree or the master theorem.
- P, NP, NP-Complete and NP-Hardlesson
Sort problems by whether a yes-answer can be found fast or only checked fast, and prove hardness by reduction.
- Recursionlesson
Break a problem into smaller calls and understand the call stack and base case.
- Tower of Hanoilesson
Move n disks in 2ⁿ − 1 moves with three lines of recursion, and see why nothing is faster.
- Data Structureslesson
How values are arranged, accessed, inserted, removed, and updated.
Linear data structures
These structures keep values in a sequence. The important difference is how each one finds, inserts, and removes an item.
Arrays
Contiguous storage: indexing is constant time, but inserting in the middle is not.
- Arrayslesson
Contiguous memory, indexes, traversal, insertion, deletion, and dynamic resizing.
- Static vs Dynamic Arrayslesson
Understand the difference between fixed-size memory blocks and auto-expanding lists.
- Multidimensional Arrayslesson
Learn how grids and matrices are mapped onto linear computer memory.
- Prefix Sumslesson
Query the sum of any subarray in constant time using a precomputed array.
- Difference Arrayslesson
Apply massive overlapping range updates in constant time per update.
- Sparse Arrayslesson
Store massive arrays efficiently when most of their elements are zero or empty.
Linked lists
Order comes from references between nodes, so inserting is cheap but indexing is not.
- Linked Listslesson
Nodes, references, traversal, insertion, deletion, and reversal.
- Singly Linked Listslesson
Master the mechanics of one-way node traversal and the fast/slow pointer technique.
- Doubly Linked Listslesson
Leverage backward pointers for O(1) deletions and complex caching structures.
- Circular Linked Listslesson
Build a continuous ring of nodes where the tail connects back to the head.
- Polynomial Addition Using Linked Listlesson
Store one node per term and add two polynomials in a single merge-like pass.
- Skip Listslesson
Achieve O(log N) search times in a linked list using multiple layers of express lanes.
Stacks
Last in, first out. The restriction is what makes execution order useful.
- Stackslesson
Array vs linked-list implementations, expression evaluation, and call-stack behaviour.
- Infix to Postfix Conversionlesson
Convert infix to postfix with one operator stack, using precedence and associativity, then evaluate it.
- Monotonic Stackslesson
Maintain a strictly increasing or decreasing invariant to solve 'next greater element' problems.
Queues
First in, first out, plus the ring buffers and double-ended variants built on it.
- Queueslesson
The First-In-First-Out processing model and its critical role in breadth-first search.
- Circular Queueslesson
Use modulo arithmetic to build efficient, fixed-size ring buffers.
- Dequeslesson
Double-ended queues allow insertion and deletion at both the front and rear.
- Monotonic Queueslesson
Combine a deque with a monotonic invariant to conquer sliding window problems.
Strings
A string is an array of characters, with its own scanning and matching techniques.
Trees, graphs, and indexed structures
Use these when relationships branch, connect in many directions, or need faster lookup than a simple scan.
Trees
Hierarchies that branch, and the balancing rules that keep them shallow.
- Treeslesson
Roots, children, depth, traversal, binary search trees, and balanced trees.
- Binary Treeslesson
Understand the foundations of binary trees, nodes, leaves, and hierarchical data.
- Binary Search Treeslesson
Learn how the BST property enables fast lookups and sorted retrievals.
- Tree Traversalslesson
Explore Pre-order, In-order, Post-order, and Level-order traversal strategies.
- Threaded Binary Treeslesson
Reuse the n + 1 null links as in-order threads and traverse with no stack.
- Expression Treeslesson
Build a tree from postfix with one stack, evaluate it, and read prefix, infix and postfix off it.
- Lowest Common Ancestorlesson
Find the deepest node that is an ancestor of two specific targets.
- Tree Diameter and Heightlesson
Calculate the longest path between any two nodes in a tree structure.
Balanced and disk-based trees
Self-balancing variants that bound height, and the wide trees built for disk.
- AVL Treeslesson
Master self-balancing trees using height differentials and rotations.
- Red-Black Treeslesson
Explore the relaxed balancing rules that power standard library maps and sets.
- Splay Treeslesson
A self-adjusting BST that splays each accessed node to the root for O(log n) amortized operations.
- B-Trees and B+ Treeslesson
Learn the wide, shallow trees designed specifically for disk storage and databases.
Indexed trees
Structures over an array that answer range queries, with or without updates, faster than a scan.
Spatial and interval trees
Trees whose nodes own a region of space or a span of values, so a query skips everything it cannot touch.
Heaps and priority queues
Keep the smallest or largest item reachable while values keep arriving.
- Heaps and Priority Queueslesson
Maintain the smallest or largest available item while values are added and removed.
- Fibonacci Heaplesson
A lazy mergeable heap: O(1) amortized insert, union and decrease-key, O(log n) extract-min.
- Priority Queueslesson
Learn how priority queues process the most urgent items first using heap structures.
Hashing and prefix structures
Constant-time lookup by key, and trees keyed on shared prefixes.
- Hash Tableslesson
Keys, hash functions, collisions, sets, maps, and constant-time lookup.
- Trieslesson
Store words by shared prefixes for lookup and autocomplete.
- Trie Operations and Applicationslesson
Build efficient prefix trees for autocomplete and string dictionaries.
- Suffix Arrayslesson
Sort all suffixes of a string to solve complex substring problems efficiently.
- Suffix Treeslesson
Compress all suffixes of a string into a powerful, navigatable Trie.
- Bloom Filterslesson
Trade absolute certainty for immense space savings in set membership queries.
Graphs
Vertices and edges, and the connectivity structures built on them.
Core algorithms
Algorithms transform or inspect the structures above. Each group below shares one idea: creating order, discarding work, scanning with indexes, or arithmetic on whole numbers.
Sorting
Ordering makes every later lookup cheaper. These lessons compare how each algorithm moves values, what it costs, and when it is the right choice.
- Sorting Algorithmslesson
Compare every sort on time, space, stability, and when to reach for it.
- In-Place vs Out-of-Place Sortinglesson
How much extra memory a sort needs, and when a fresh copy is worth it.
- Stable vs Unstable Sortinglesson
What a sort does with equal keys, which sorts keep their order, and sorting by several keys.
- Bubble Sortlesson
Swap adjacent pairs each pass, and stop early when a pass makes no swap.
- Selection Sortlesson
Scan the unsorted tail for its minimum, then place it in one swap.
- Insertion Sortlesson
Grow a sorted prefix by shifting larger values right — fast on nearly sorted data.
- Merge Sortlesson
Split to single values, then merge sorted runs in guaranteed O(n log n).
- Quick Sortlesson
Partition around a pivot, and see why pivot choice decides the worst case.
- Quickselectlesson
Partition once, keep the side that holds position k, and find the k-th smallest in O(n) on average.
- Heap Sortlesson
Build a max-heap in place, then repeatedly extract the root.
- Counting Sortlesson
Count occurrences instead of comparing, for small integer ranges.
- Radix Sortlesson
Sort digit by digit with a stable pass per position.
- Bucket Sortlesson
Spread values across buckets, sort each, then concatenate.
- Shell Sortlesson
Insertion sort over shrinking gaps, moving values far in one step.
Searching
Once data is ordered, a search can discard half the remaining candidates at every step instead of scanning them all.
- Searching Algorithmslesson
Linear search, binary search, and the conditions that make binary search valid.
- Linear Searchlesson
Check each value in turn: the cost of a hit, a miss, and the sentinel trick.
- Binary Searchlesson
Halve the search space each step, and get the boundary conditions right.
- Jump Searchlesson
Hop along block ends, step back once, and walk one block of size √n.
- Interpolation Searchlesson
Guess the position from the value: fast on even data, slow on skewed data.
- Exponential Searchlesson
Double the index until it overshoots, then binary search the last bracket.
- Ternary Searchlesson
Find the peak of a one-hump function by dropping a third of the range each round.
- Binary Search on Answerlesson
Guess a result, check it in one pass, and halve the range of possible answers.
- Binary Search Variationslesson
First and last occurrence, rotated arrays and peaks: change which half you keep.
Scanning with indexes
One pass, two moving positions. These techniques avoid rescanning a sequence that has already been examined.
- Two Pointerslesson
Move two indexes through a sequence without repeatedly rescanning it.
- Sliding Windowlesson
Maintain a changing range while adding and removing boundary values.
- Fixed Size Sliding Windowlesson
Keep k values in view: one enters, one leaves, and the summary updates in O(1).
- Variable Size Sliding Windowlesson
Grow on the right, shrink on the left until the condition holds: shortest, longest and counts.
- Advanced Two Pointerslesson
Fix one value and sweep a pair, split an array three ways, or walk two arrays at once.
- Fast and Slow Pointerslesson
Walk a list at two speeds to detect a loop, find where it starts, or stop at the middle.
String matching
Find a pattern inside a longer text without restarting the comparison after every mismatch.
Number theory
Arithmetic on whole numbers: divisibility, primes, modular results, and the identities that keep them fast.
String algorithms
Linear-time scanning of text: match a pattern, measure palindromes, or compare substrings in constant time.
- Z-Algorithmlesson
Compute, for every position, how far the string matches its own prefix — in one linear pass.
- Manacher's Algorithmlesson
Find every palindromic radius in linear time by mirroring inside the rightmost known palindrome.
- String Hashinglesson
Reduce a substring comparison to one arithmetic difference, and handle collisions honestly.
Numbers and counting
The arithmetic a competitive or interview problem assumes you already know.
- Modular Arithmeticlesson
Work in congruence classes, and invert a multiplication when division is unavailable.
- Combinatorics Basicslesson
Count arrangements and selections by argument rather than enumeration, using Pascal's rule.
- Matrix Exponentiationlesson
Advance a linear recurrence in logarithmic time by squaring its transition matrix.
- Randomized Algorithmslesson
Use randomness for correctness in expectation — shuffling, sampling, and why the range must shrink.
Problem-solving methods
These methods apply when a direct scan is not enough: the problem has overlapping subproblems, a safe local choice, or a structure of connections to explore.
Recursion and reuse
Split a problem into smaller versions of itself, avoid solving the same version twice, and undo a choice that leads nowhere.
- Divide and Conquerlesson
Split independent subproblems, solve recursively, and analyze the combine recurrence.
- Closest Pair of Pointslesson
Split by x, solve each half, then check a 2δ strip where only 7 neighbours matter.
- Dynamic Programminglesson
Save answers to repeated subproblems and build the final answer from them.
- One-Dimensional Dynamic Programminglesson
One index, one array: define dp[i], fill it left to right, then shrink it to two variables.
- Longest Increasing Subsequencelesson
From the O(n²) look-back to patience piles and binary search in O(n log n), plus printing the sequence.
- Kadane's Algorithmlesson
Find the maximum subarray sum in one pass by keeping the best sum ending at each index.
- Rod Cutting Problemlesson
Pick cut lengths to maximise total price, reusing the best price of every shorter rod.
- Memoizationlesson
Turn repeated recursive states into explicit cache hits and misses.
- Memoization vs Tabulationlesson
Run one recurrence top-down with a cache or bottom-up with a loop, and see when each wins.
- 0/1 Knapsacklesson
Take or skip each item once; a table of capacities, then one row looped backward.
- Unbounded Knapsacklesson
Unlimited copies of each item: the same one-row loop, run forward instead of backward.
- Backtrackinglesson
Choose, explore, undo, and continue through combinations and arrangements.
- Backtracking Foundationslesson
Write the choose, explore, unchoose template from three questions, prune before each call, and count its cost.
- Generating Permutationslesson
Fill one position at a time with an unused item, handle repeated values, and compare Heap's swap order.
- Subsets and Combinationslesson
List every subset or every choice of k items with a loop that only moves forward, or count through bitmasks.
- Constraint-Based Backtrackinglesson
Variables, domains and constraints: forward checking and fewest-options-first ordering on a small Sudoku.
- Branch and Boundlesson
Prune every branch whose optimistic bound cannot beat the best answer found so far.
- Hamiltonian Cyclelesson
Visit every vertex exactly once and return, found by backtracking over vertex orders.
Making local choices
Commit to the best option available right now, and justify why that choice cannot be regretted later.
- Greedy Algorithmslesson
Make the best safe local choice and explain why it cannot damage the final answer.
- Greedy Algorithm Foundationslesson
Prove a greedy rule with an exchange argument, and read the right sort key off one swap.
- Huffman Codinglesson
Merge the two least frequencies repeatedly to build an optimal prefix tree.
- Activity Selection Problemlesson
Sort by finish time, take every compatible activity, and prove the greedy choice is safe.
- Interval Algorithmslesson
One overlap test and the right sort order: merge, insert, intersect and trim ranges in one pass.
- Sweep Line Algorithmlesson
Turn ranges into start and end events, scan once, and read off the peak overlap and covered length.
Graph traversal
Visit every reachable vertex in a defined order. That order is what makes the rest of graph work possible.
- Advanced Graph Algorithmslesson
Shortest paths, topological ordering, minimum spanning trees, and connectivity.
- Breadth-First Searchlesson
Explore a graph level by level with a queue and visited set.
- Depth-First Searchlesson
Grow and unwind the active call stack while exploring a graph.
- Bipartite Graph Checkinglesson
Give neighbours opposite sides with BFS, and print the odd cycle when two neighbours clash.
- Strongly Connected Componentslesson
Split a directed graph into groups of mutually reachable vertices with Kosaraju's two-pass DFS or Tarjan's single pass.
- Kosaraju's Algorithmlesson
Record DFS finish order, reverse every edge, and search again from the last vertex to finish.
- Tarjan's Algorithmlesson
One DFS with discovery times, low-link values and a stack that pops each component whole.
- Articulation Points and Bridgeslesson
Find the vertices and edges whose removal disconnects a graph, in one DFS using discovery times and low values.
- Bridges in a Graphlesson
Find every edge on no cycle in one DFS with the low[v] > disc[u] test, parallel edges included.
- Topological Sortlesson
Drain in-degrees with Kahn's algorithm or reverse DFS finish order.
- Cycle Detectionlesson
Use directed colors or undirected union-find to expose cycle witnesses.
- Directed Graph Cycle Detectionlesson
Three vertex states, four kinds of edge, and printing the loop a back edge closes.
- Undirected Graph Cycle Detectionlesson
Skip the edge you came in on, count edges against vertices, or merge sets until two ends already match.
- Eulerian Paths and Circuitslesson
Use every edge exactly once: the even-degree test, then Hierholzer's walk-and-splice.
Shortest paths and spanning trees
Weighted graphs: reach every vertex as cheaply as possible, or connect them all for the least total cost.
- Unweighted Shortest Pathlesson
Fewest edges from a source by BFS: distances, the path from parent links, and path counts.
- Dijkstra's Algorithmlesson
Finalize nonnegative shortest paths with a min-heap and distance table.
- 0-1 BFSlesson
Shortest paths when every edge costs 0 or 1: a deque instead of a heap, in O(V + E).
- Bellman–Ford Algorithmlesson
Relax every edge and expose a reachable negative cycle on the extra pass.
- Floyd–Warshall Algorithmlesson
All-pairs shortest paths by admitting one middle vertex per round, in O(V³).
- Minimum Spanning Treelesson
Build an MST with Kruskal and Prim while rejecting cycle edges.
- Kruskal's Algorithmlesson
Sort edges by weight and keep each one that joins two components, tracked with union-find.
- Prim's Algorithmlesson
Grow one tree from any vertex, always adding the cheapest edge leaving it via a min-heap.
Bitwise techniques
Treat an integer as a row of flags and let single hardware instructions do the set operations.
Advanced dynamic programming
Once a state is more than one index, the shape of that state is the whole design decision.
- Two-Dimensional Dynamic Programminglesson
Fill a table whose state is a pair of coordinates, in an order that respects dependencies.
- Grid Dynamic Programminglesson
Count paths around walls on a grid, one cell from the cell above and the cell to its left.
- Longest Common Subsequencelesson
Compare last letters, fill one cell per prefix pair, then walk back to print the letters.
- Edit Distancelesson
Fewest inserts, deletes and replaces between two strings, one table cell per prefix pair.
- Optimal Binary Search Treelesson
Place frequently searched keys near the root by trying every root of every key range.
- Bitmask Dynamic Programminglesson
Let an integer's bits name a visited subset, and iterate over subsets instead of positions.
- Travelling Salesman Problemlesson
Cut n! tours to n²·2ⁿ steps with Held–Karp dynamic programming over visited sets.
- Tree Dynamic Programminglesson
Combine independent child answers in one post-order pass, with rerooting when every root matters.
- Digit Dynamic Programminglesson
Count numbers by fixing digits left to right, carrying only whether the prefix is still tight.
Flows, colouring, and heuristics
Graph problems that are not shortest paths: how much can flow, how few colours are needed, and how to search with an estimate.
- A* Searchlesson
Order the frontier by cost so far plus an admissible estimate of the cost remaining.
- Network Flow and Maximum Flowlesson
Augment along residual paths, and see why the reverse edge is what makes it correct.
- Graph Colouringlesson
Assign the smallest safe colour greedily, and understand why that is a bound, not the optimum.
- Johnson's Algorithmlesson
Reweight edges with vertex potentials so Dijkstra runs safely on a graph with negative weights.