Skip to the content.

DSA Visualized: Data Structures and Algorithms Explained with Diagrams and Step-by-Step Traces

DSA Visualized is a free, open-source guide to data structures and algorithms for students, self-taught developers and anyone preparing for coding interviews. Each of the 33 topics comes with a plain-English explanation, a Mermaid diagram that renders right on GitHub, a step-by-step trace table on a small concrete input, time and space complexity, and a short, tested Python reference implementation.

Every trace in this repository is produced by running the actual Python code in dsa/, and the test suite checks the code against Python’s standard library and brute force. If a table says the heap looks like [1, 3, 2, 5, 9, 8] after six pushes, that is what the code really produced.

Last reviewed: December 2026

Table of Contents

How to Use This Guide

  1. Read the explanation, then look at the diagram and predict what the algorithm will do.
  2. Cover the trace table and work the example by hand on paper. Then compare row by row. This is the fastest way to find gaps in your understanding.
  3. Type the Python implementation yourself instead of copying it. Run it on the same input and check that you get the same result.
  4. Change the input in tools/build.py, rebuild, and watch how the trace changes (see Run the Code and Tests).

Topics are ordered so each one builds on earlier ones: linear structures, then trees, then graphs, then sorting, then problem-solving techniques and dynamic programming. The short version of each topic is below; click through to the full page for the trace, code and common mistakes.

Big-O Cheat Sheet

Structure / algorithm Access Search Insert Delete Notes
Array / dynamic array O(1) O(n) O(1) amortized at end, O(n) middle O(n) Contiguous memory
Linked list O(n) O(n) O(1) after a known node O(1) after a known node No random access
Stack / queue / deque top/ends O(1) O(n) O(1) O(1) Use list for stacks, deque for queues
Hash table - O(1) average O(1) average O(1) average O(n) worst case with many collisions
Balanced BST O(log n) O(log n) O(log n) O(log n) Sorted order via inorder traversal
Binary heap min O(1) O(n) O(log n) pop min O(log n) Priority queue; heapq in Python
Trie - O(L) O(L) O(L) L = word length
Union-find - find ~O(1) union ~O(1) - With path compression + union by size
Algorithm Time Extra space Stable?
Bubble sort O(n^2), O(n) best O(1) yes
Insertion sort O(n^2), O(n) best O(1) yes
Merge sort O(n log n) O(n) yes
Quick sort O(n log n) average, O(n^2) worst O(log n) no
Heap sort O(n log n) O(1) no
Python sorted (Timsort) O(n log n), O(n) on sorted runs O(n) yes
Binary search O(log n) O(1) -
BFS / DFS O(V + E) O(V) -
Dijkstra (binary heap) O((V + E) log V) O(V + E) -
Topological sort O(V + E) O(V) -

Rule of thumb from input size (typical interview and judge limits, about 10^8 simple operations per second):

n up to Usually fine
10 to 12 O(n!) permutations, O(2^n * n)
20 to 25 O(2^n) subsets, bitmask DP
500 O(n^3)
5,000 O(n^2)
10^5 to 10^6 O(n log n) or O(n)
10^9 and more O(log n) or O(1) math

Which Technique Should I Use?

flowchart TD
    Q["Read the problem"] --> S{"Input sorted, or answer monotonic?"}
    S -->|yes| BS["Binary search or two pointers"]
    S -->|no| C{"Contiguous subarray or substring?"}
    C -->|yes| SW["Sliding window or prefix sums"]
    C -->|no| G{"Nodes and connections?"}
    G -->|yes| W{"Weighted edges?"}
    W -->|yes| DJ["Dijkstra"]
    W -->|no| DEP{"Dependencies or ordering?"}
    DEP -->|yes| TS["Topological sort"]
    DEP -->|no| BF["BFS for shortest steps, DFS or union-find for connectivity"]
    G -->|no| A{"All combinations or arrangements?"}
    A -->|yes| BT["Backtracking"]
    A -->|no| O{"Optimal count or cost with overlapping subproblems?"}
    O -->|yes| DP["Dynamic programming"]
    O -->|no| H{"Repeated min or max, or top k?"}
    H -->|yes| HP["Heap"]
    H -->|no| HM["Hash map or set, then think again"]

Topics

Data structures

1. Arrays and Dynamic Arrays

A block of contiguous memory with O(1) access by index. A dynamic array (Python list, Java ArrayList, C++ vector) doubles its capacity when full, so appending stays O(1) on average.

flowchart LR
    s0["capacity 1: 10"]
    s1["capacity 2: 10 20"]
    s2["capacity 4: 10 20 30 _"]
    s3["capacity 4: 10 20 30 40"]
    s4["capacity 8: 10 20 30 40 50 _ _ _"]
    s0 -->|"append 20: full, copy 1"| s1
    s1 -->|"append 30: full, copy 2"| s2
    s2 -->|"append 40: room left"| s3
    s3 -->|"append 50: full, copy 4"| s4

Complexity: Read / write a[i]: O(1) time, O(1) space. Full explanation, step-by-step trace and Python code

2. Linked Lists (Reversal)

Nodes that each hold a value and a pointer to the next node. Inserting next to a node you already hold is O(1), but finding the i-th node is O(n). Reversal with three pointers is the classic warm-up.

flowchart LR
    subgraph before["Before"]
    a1["1"] --> a2["2"] --> a3["3"] --> a4["4"] --> a5["None"]
    end
    subgraph after["After reverse"]
    b4["4"] --> b3["3"] --> b2["2"] --> b1["1"] --> b5["None"]
    end

Complexity: Access i-th node: O(n) time, O(1) space. Full explanation, step-by-step trace and Python code

3. Stacks (Balanced Brackets)

Last in, first out. Push and pop at the top in O(1). Stacks power undo, function calls, expression parsing and bracket matching.

flowchart TD
    R["Read next char"] --> O{"Opening bracket?"}
    O -->|yes| P["Push it"] --> R
    O -->|no| C{"Top of stack is its opener?"}
    C -->|yes| Q["Pop"] --> R
    C -->|no| F["Unbalanced"]
    R -->|no chars left| E{"Stack empty?"}
    E -->|yes| T["Balanced"]
    E -->|no| F

Complexity: Push / pop / peek: O(1) time, O(1) space. Full explanation, step-by-step trace and Python code

4. Queues (Two-Stack Queue)

First in, first out. Enqueue at the back, dequeue at the front. In Python use collections.deque; the classic interview twist builds a queue from two stacks.

flowchart LR
    E["enqueue x"] --> I["inbox stack"]
    I -->|"only when outbox is empty: pop all and push"| O["outbox stack"]
    O --> D["dequeue returns the top of outbox"]

Complexity: Enqueue: O(1) time, O(1) space. Full explanation, step-by-step trace and Python code

5. Hash Tables (Separate Chaining)

Turn a key into a bucket index with a hash function, then store the pair there. Average O(1) insert, lookup and delete; collisions are handled with chains or probing.

flowchart LR
    b0["bucket 0"]
    b0 --> e0["empty"]
    b1["bucket 1"]
    b1 --> k_fish["fish: 4"]
    b2["bucket 2"]
    b2 --> k_cat["cat: 1"]
    k_cat --> k_bird["bird: 3"]
    b3["bucket 3"]
    b3 --> e3["empty"]
    b4["bucket 4"]
    b4 --> k_dog["dog: 9"]
    k_dog --> k_cow["cow: 5"]

Complexity: Insert / lookup / delete (average): O(1) time, O(n) total space. Full explanation, step-by-step trace and Python code

6. LRU Cache (Hash Map + Doubly Linked List)

A fixed-size cache that evicts the least recently used key. A hash map gives O(1) lookup and a doubly linked list keeps keys in usage order, so get and put are both O(1).

flowchart LR
    M["hash map: key to node"] -.-> N1
    M -.-> N2
    H["head sentinel"] --> N1["key 3: least recent"]
    N1 --> N2["key 4: most recent"]
    N2 --> T["tail sentinel"]
    T -->|"next put of a new key evicts"| N1

Complexity: get / put: O(1) time, O(capacity) space. Full explanation, step-by-step trace and Python code

Trees

7. Binary Trees and Traversals

Each node has up to two children. The four traversals (preorder, inorder, postorder, level order) are the building blocks of almost every tree problem.

graph TD
    n_1["1"]
    n_1 -->|L| n_2
    n_1 -->|R| n_3
    n_3["3"]
    n_3 -->|R| n_6
    n_6["6"]
    n_2["2"]
    n_2 -->|L| n_4
    n_2 -->|R| n_5
    n_5["5"]
    n_4["4"]

Complexity: Any traversal: O(n) time, O(h) stack, O(w) queue for BFS space. Full explanation, step-by-step trace and Python code

8. Binary Search Trees

A binary tree where every left descendant is smaller and every right descendant is larger (or equal). Search, insert and delete follow one root-to-leaf path: O(log n) if balanced, O(n) if not.

graph TD
    n_8["8"]
    n_8 -->|L| n_3
    n_8 -->|R| n_10
    n_10["10"]
    n_10 -->|R| n_14
    n_14["14"]
    n_14 -->|L| n_13
    n_13["13"]
    n_3["3"]
    n_3 -->|L| n_1
    n_3 -->|R| n_6
    n_6["6"]
    n_6 -->|L| n_4
    n_6 -->|R| n_7
    n_7["7"]
    n_4["4"]
    n_1["1"]

Complexity: Search / insert / delete (balanced): O(log n) time, O(1) iterative space. Full explanation, step-by-step trace and Python code

9. Heaps and Priority Queues

A complete binary tree stored in an array where every parent is smaller than its children (min-heap). The minimum is always at index 0; push and pop are O(log n).

graph TD
    n_0["index 0: 3"]
    n_0 -->|L| n_1
    n_0 -->|R| n_2
    n_2["index 2: 8"]
    n_1["index 1: 5"]
    n_1 -->|L| n_3
    n_3["index 3: 9"]

Complexity: Peek min: O(1) time, O(1) space. Full explanation, step-by-step trace and Python code

10. Tries (Prefix Trees)

A tree of characters where each path from the root spells a prefix. Lookups cost O(length of the word), independent of how many words are stored. Used for autocomplete and word games.

graph TD
    root["root"]
    t_d["d"]
    root --> t_d
    t_c["c"]
    root --> t_c
    t_ca["a"]
    t_c --> t_ca
    t_cat["t - end of cat"]
    t_ca --> t_cat
    t_car["r - end of car"]
    t_ca --> t_car
    t_cart["t - end of cart"]
    t_car --> t_cart
    t_do["o"]
    t_d --> t_do
    t_dog["g - end of dog"]
    t_do --> t_dog

Complexity: Insert / search / startsWith (word length L): O(L) time, O(L) new nodes for insert space. Full explanation, step-by-step trace and Python code

11. Fenwick Tree (Binary Indexed Tree)

An array where entry i stores the sum of a block of positions ending at i, sized by i’s lowest set bit. Prefix sums and point updates both take O(log n) with a few lines of code.

graph BT
    f1["tree 1: positions 1 to 1, sum 3"]
    f2["tree 2: positions 1 to 2, sum 5"]
    f3["tree 3: positions 3 to 3, sum -1"]
    f4["tree 4: positions 1 to 4, sum 10"]
    f5["tree 5: positions 5 to 5, sum 5"]
    f6["tree 6: positions 5 to 6, sum 9"]
    f7["tree 7: positions 7 to 7, sum -3"]
    f8["tree 8: positions 1 to 8, sum 19"]
    f1 --> f2
    f2 --> f4
    f3 --> f4
    f4 --> f8
    f5 --> f6
    f6 --> f8
    f7 --> f8

Complexity: prefix_sum / range_sum: O(log n) time, O(1) space. Full explanation, step-by-step trace and Python code

12. Segment Tree (Range Sum Queries)

A binary tree where each node stores an aggregate (sum, min, max) of an index range. Range queries and point updates are O(log n), and the aggregate can be anything associative.

graph TD
    s1["range 0 to 5: sum 21"]
    s2["range 0 to 2: sum 8"]
    s4["range 0 to 1: sum 3"]
    s8["range 0 to 0: sum 2"]
    s9["range 1 to 1: sum 1"]
    s4 --> s8
    s4 --> s9
    s5["range 2 to 2: sum 5"]
    s2 --> s4
    s2 --> s5
    s3["range 3 to 5: sum 13"]
    s6["range 3 to 4: sum 7"]
    s12["range 3 to 3: sum 3"]
    s13["range 4 to 4: sum 4"]
    s6 --> s12
    s6 --> s13
    s7["range 5 to 5: sum 6"]
    s3 --> s6
    s3 --> s7
    s1 --> s2
    s1 --> s3

Complexity: Range query: O(log n) time, O(log n) recursion space. Full explanation, step-by-step trace and Python code

Graphs

13. Graphs: Breadth-First Search (BFS)

Explore a graph in rings: first all neighbors, then their neighbors, using a queue. BFS finds the shortest path (fewest edges) in an unweighted graph.

graph LR
    A --- B
    A --- C
    B --- D
    B --- E
    C --- F
    E --- F

Complexity: BFS over V nodes and E edges: O(V + E) time, O(V) space. Full explanation, step-by-step trace and Python code

14. Graphs: Depth-First Search (DFS)

Go as deep as possible along one path before backing up. DFS is the tool for connected components, cycle detection, path existence and exhaustive search.

graph LR
    A --- B
    A --- C
    B --- D
    B --- E
    C --- F
    E --- F

Complexity: DFS over V nodes and E edges: O(V + E) time, O(V) for visited set and stack space. Full explanation, step-by-step trace and Python code

15. Dijkstra’s Shortest Path

Shortest paths from one source in a graph with non-negative edge weights. Always expand the closest unfinished node, using a min-heap.

graph LR
    A -->|4| B
    A -->|1| C
    B -->|1| D
    C -->|2| B
    C -->|5| D
    D -->|3| E

Complexity: Dijkstra with a binary heap: O((V + E) log V) time, O(V + E) space. Full explanation, step-by-step trace and Python code

16. Topological Sort (Kahn’s Algorithm)

Order the nodes of a directed acyclic graph so every edge points forward. Used for build systems, course prerequisites and task scheduling.

graph LR
    A --> B
    A --> C
    B --> D
    B --> E
    C --> D
    D --> F
    E --> F

Complexity: Kahn’s algorithm: O(V + E) time, O(V) space. Full explanation, step-by-step trace and Python code

17. Union-Find (Disjoint Set Union)

Track which items belong to the same group while groups merge. With path compression and union by size, each operation is nearly O(1).

graph BT
    u0["0"]
    u1["1"]
    u2["2"]
    u3["3"]
    u4["4"]
    u5["5"]
    u1 --> u0
    u2 --> u0
    u3 --> u0
    u5 --> u4

Complexity: find / union with both optimizations: O(alpha(n)), effectively constant time, O(n) space. Full explanation, step-by-step trace and Python code

18. Minimum Spanning Tree (Kruskal’s Algorithm)

Connect every node of a weighted undirected graph with the cheapest possible set of edges and no cycles. Kruskal’s algorithm sorts edges by weight and keeps each one that joins two different components, using union-find.

graph LR
    A ---|4| B
    A ===|1| C
    B ===|2| C
    B ===|5| D
    C ---|8| D
    C ---|10| E
    D ===|2| E
    B ---|6| E

Complexity: Kruskal (sort + union-find): O(E log E) time, O(V + E) space. Full explanation, step-by-step trace and Python code

Sorting

19. Bubble Sort

Repeatedly swap adjacent items that are out of order. Each pass bubbles the largest remaining item to the end. O(n^2), mainly a teaching tool.

flowchart LR
    s0["5 2 9 1 6 3"]
    s1["2 5 1 6 3 9"]
    s2["2 1 5 3 6 9"]
    s3["1 2 3 5 6 9"]
    s4["1 2 3 5 6 9"]
    s0 -->|"pass 1"| s1
    s1 -->|"pass 2"| s2
    s2 -->|"pass 3"| s3
    s3 -->|"pass 4"| s4

Complexity: Worst / average: O(n^2) time, O(1) space. Full explanation, step-by-step trace and Python code

20. Insertion Sort

Grow a sorted prefix one item at a time, shifting bigger items right to make room. O(n^2) worst case but very fast on small or nearly sorted arrays.

flowchart LR
    s0["5 2 9 1 6 3"]
    s1["2 5 9 1 6 3"]
    s2["2 5 9 1 6 3"]
    s3["1 2 5 9 6 3"]
    s4["1 2 5 6 9 3"]
    s5["1 2 3 5 6 9"]
    s0 -->|"insert 2"| s1
    s1 -->|"insert 9"| s2
    s2 -->|"insert 1"| s3
    s3 -->|"insert 6"| s4
    s4 -->|"insert 3"| s5

Complexity: Worst / average: O(n^2) time, O(1) space. Full explanation, step-by-step trace and Python code

21. Merge Sort

Split the array in half, sort each half recursively, then merge the two sorted halves. Always O(n log n) and stable, at the cost of O(n) extra memory.

graph TD
    m["5 2 9 1 6 3"]
    ml["5 2 9"]
    mll["5"]
    ml --> mll
    mlr["2 9"]
    mlrl["2"]
    mlr --> mlrl
    mlrr["9"]
    mlr --> mlrr
    ml --> mlr
    m --> ml
    mr["1 6 3"]
    mrl["1"]
    mr --> mrl
    mrr["6 3"]
    mrrl["6"]
    mrr --> mrrl
    mrrr["3"]
    mrr --> mrrr
    mr --> mrr
    m --> mr

Complexity: All cases: O(n log n) time, O(n) space. Full explanation, step-by-step trace and Python code

22. Quick Sort

Pick a pivot, partition the array into smaller and larger items, then sort both sides. O(n log n) on average, in place, and usually the fastest comparison sort in practice.

graph TD
    q1["range 0..5: 5 2 9 1 6 3, pivot 3 lands at 2"]
    q2["range 0..1: 2 1, pivot 1 lands at 0"]
    q3["range 3..5: 5 6 9, pivot 9 lands at 5"]
    q4["range 3..4: 5 6, pivot 6 lands at 4"]
    q1 -->|left part| q2
    q1 -->|right part| q3
    q3 -->|left part| q4

Complexity: Average: O(n log n) time, O(log n) recursion space. Full explanation, step-by-step trace and Python code

23. Heap Sort

Build a max-heap in place, then repeatedly swap the max to the end and shrink the heap. O(n log n) in all cases with O(1) extra memory, but not stable.

flowchart TD
    s0["start: heap 5 2 9 1 6 3 / sorted none"]
    s1["build: heap 5 2 9 1 6 3 / sorted none"]
    s2["build: heap 5 6 9 1 2 3 / sorted none"]
    s3["build: heap 9 6 5 1 2 3 / sorted none"]
    s4["extract: heap 6 3 5 1 2 / sorted 9"]
    s5["extract: heap 5 3 2 1 / sorted 6 9"]
    s6["extract: heap 3 1 2 / sorted 5 6 9"]
    s7["extract: heap 2 1 / sorted 3 5 6 9"]
    s8["extract: heap 1 / sorted 2 3 5 6 9"]
    s0 -->|"sift down index 2"| s1
    s1 -->|"sift down index 1"| s2
    s2 -->|"sift down index 0"| s3
    s3 -->|"swap max 9 to index 5"| s4
    s4 -->|"swap max 6 to index 4"| s5
    s5 -->|"swap max 5 to index 3"| s6
    s6 -->|"swap max 3 to index 2"| s7
    s7 -->|"swap max 2 to index 1"| s8

Complexity: All cases: O(n log n) time, O(1) space. Full explanation, step-by-step trace and Python code

Techniques

Halve a sorted search range each step by comparing with the middle item. O(log n). The same idea finds the smallest value that satisfies any monotonic condition.

flowchart LR
    s0["lo 0 hi 8 mid 4, value 9"]
    s1["lo 5 hi 8 mid 6, value 13"]
    s2["lo 7 hi 8 mid 7, value 15"]
    s3["found at index 7"]
    s0 -->|"too small, go right"| s1
    s1 -->|"too small, go right"| s2
    s2 -->|"equal"| s3

Complexity: Search in sorted array: O(log n) time, O(1) space. Full explanation, step-by-step trace and Python code

25. Two Pointers

Move two indices through an array, usually from both ends toward the middle, to replace an O(n^2) pair search with one O(n) pass. Works when the input is sorted or has another monotonic property.

flowchart TD
    S["sum = a at left + a at right"] --> Q{"Compare sum with target"}
    Q -->|equal| F["Return the pair"]
    Q -->|"too small"| L["left moves right"] --> S
    Q -->|"too big"| R["right moves left"] --> S

Complexity: Pair sum on sorted array: O(n) time, O(1) space. Full explanation, step-by-step trace and Python code

26. Sliding Window

Keep a contiguous window [left, right] and slide it across the input, growing on the right and shrinking on the left, to answer ‘longest/shortest subarray or substring with property X’ in O(n).

flowchart TD
    A["Move right one step, read char"] --> B{"char seen inside window?"}
    B -->|yes| C["left jumps past its previous index"] --> D
    B -->|no| D["Record index of char"]
    D --> E["best = max of best and window length"] --> A

Complexity: Variable-size window: O(n) time, O(size of alphabet) space. Full explanation, step-by-step trace and Python code

27. Prefix Sums (Subarray Sum Equals K)

Precompute running totals so the sum of any range is one subtraction. Combined with a hash map, prefix sums count subarrays with a target sum in O(n), even with negative numbers.

flowchart LR
    P0["prefix before l"] -->|"items l to r"| P1["prefix after r"]
    P1 --> S["range sum = prefix after r minus prefix before l"]
    S --> K{"equals k?"}
    K -->|"look up prefix minus k in the hash map"| C["add its count"]

Complexity: Build prefix array: O(n) time, O(n) space. Full explanation, step-by-step trace and Python code

28. Monotonic Stack (Next Greater Element)

A stack kept in sorted order. Each new item pops every item it beats, and those pops are exactly the answers to ‘next greater’ or ‘next smaller’ questions, all in O(n).

flowchart TD
    A["Read next value x"] --> B{"Stack top value smaller than x?"}
    B -->|yes| C["Pop it: its answer is x"] --> B
    B -->|no| D["Push index of x"] --> A
    A -->|"input done"| E["Indices left on the stack get -1"]

Complexity: Next greater / smaller for all items: O(n) time, O(n) space. Full explanation, step-by-step trace and Python code

29. KMP String Matching

Find a pattern in a text in O(n + m) by never moving backwards in the text. A precomputed prefix table tells the matcher how far to fall back after a mismatch.

flowchart TD
    A["Compare text at i with pattern at j"] --> B{"Equal?"}
    B -->|yes| C["j plus 1, then i plus 1"] --> D{"j equals pattern length?"}
    D -->|yes| M["Report match, j = lps at j minus 1"] --> A
    D -->|no| A
    B -->|"no, j above 0"| F["Fall back: j = lps at j minus 1"] --> A
    B -->|"no, j is 0"| G["i plus 1"] --> A

Complexity: Prefix function: O(m) time, O(m) space. Full explanation, step-by-step trace and Python code

30. Recursion and the Call Stack

A function that solves a problem by calling itself on a smaller input, plus a base case that stops it. Every call waits on the call stack until its sub-call returns.

graph TD
    f4["factorial 4"] -->|calls| f3["factorial 3"]
    f3 -->|calls| f2["factorial 2"]
    f2 -->|calls| f1["factorial 1: base case"]
    f1 -.->|returns 1| f2
    f2 -.->|returns 2| f3
    f3 -.->|returns 6| f4

Complexity: factorial(n): O(n) time, O(n) call stack space. Full explanation, step-by-step trace and Python code

31. Backtracking (Subsets)

Build a solution one choice at a time; after exploring a choice, undo it and try the next. Generates subsets, permutations and combinations, and solves constraint puzzles like N-Queens and Sudoku.

graph TD
    p_root["empty"]
    p_1["1"]
    p_1_2["1 2"]
    p_1_2_3["1 2 3"]
    p_1_2 -->|add 3| p_1_2_3
    p_1 -->|add 2| p_1_2
    p_1_3["1 3"]
    p_1 -->|add 3| p_1_3
    p_root -->|add 1| p_1
    p_2["2"]
    p_2_3["2 3"]
    p_2 -->|add 3| p_2_3
    p_root -->|add 2| p_2
    p_3["3"]
    p_root -->|add 3| p_3

Complexity: Subsets of n items: O(n * 2^n) time, O(n) recursion plus output space. Full explanation, step-by-step trace and Python code

Dynamic programming

32. Dynamic Programming 1D (Coin Change)

Solve each subproblem once, store the answer, and build bigger answers from smaller ones. Coin change finds the fewest coins for an amount, where greedy choices fail.

flowchart LR
    d0["dp 0 = 0"]
    d1["dp 1 = 1"]
    d2["dp 2 = 2"]
    d3["dp 3 = 1"]
    d4["dp 4 = 1"]
    d5["dp 5 = 2"]
    d6["dp 6 = 2"]
    d0 -->|"+1"| d1
    d1 -->|"+1"| d2
    d2 -->|"+1"| d3
    d0 -->|"+3"| d3
    d3 -->|"+1"| d4
    d1 -->|"+3"| d4
    d0 -->|"+4"| d4
    d4 -->|"+1"| d5
    d2 -->|"+3"| d5
    d1 -->|"+4"| d5
    d5 -->|"+1"| d6
    d3 -->|"+3"| d6
    d2 -->|"+4"| d6

Complexity: Coin change, n coins, amount A: O(n * A) time, O(A) space. Full explanation, step-by-step trace and Python code

33. Dynamic Programming 2D (Longest Common Subsequence)

A 2D table where cell (i, j) answers the problem for the first i characters of one string and the first j of the other. LCS is the base of diff tools and edit-distance style problems.

flowchart TD
    S["Cell i, j"] --> Q{"x at i-1 equals y at j-1?"}
    Q -->|yes| D["Diagonal cell plus 1"]
    Q -->|no| M["Max of cell above and cell to the left"]

Complexity: LCS of lengths m and n: O(m * n) time, O(m * n), or O(min(m, n)) for length only space. Full explanation, step-by-step trace and Python code

Run the Code and Tests

Everything uses the Python standard library only (Python 3.9 or newer).

# run the test suite (algorithms vs. stdlib and brute force, traces, Mermaid lint)
python3 -m unittest discover -s tests -v

# regenerate README.md and topics/*.md from the code
python3 tools/build.py

# verify the generated pages are up to date (used by the tests too)
python3 tools/build.py --check

Repository layout:

Path What is inside
dsa/structures.py Arrays, linked lists, stacks, queues, hash table, trees, BST, heap, trie, union-find
dsa/graphs.py BFS, DFS, Dijkstra, topological sort
dsa/sorting.py Bubble, insertion, merge, quick and heap sort
dsa/techniques.py Binary search, two pointers, sliding window, recursion, backtracking, dynamic programming
dsa/advanced.py LRU cache, Fenwick tree, segment tree, Kruskal MST, prefix sums, monotonic stack, KMP
tools/build.py Topic text, diagrams and inputs; renders the Markdown pages
tests/ unittest tests for every algorithm and for the generated docs
topics/ One generated page per topic

To change an example, edit its input in tools/build.py, run the build, and the trace tables update automatically. Do not edit files in topics/ or this README by hand; they are overwritten by the build.

Study Plan: 4 Weeks Through This Repo

About one hour a day. Each day: read the topic, work the trace by hand, type the code from memory, then solve two practice problems that use it.

Week Topics Practice focus
1 1 to 6: arrays, linked lists, stacks, queues, hash tables, LRU cache Hash map counting, bracket matching, list reversal, design an LRU cache
2 7 to 12: tree traversals, BST, heaps, tries, Fenwick tree, segment tree Tree recursion, top-k with a heap, prefix search, range queries
3 13 to 18 and 24 to 29: graphs, then binary search and array techniques Grid BFS, course schedule, shortest path, windows, prefix sums
4 19 to 23 and 30 to 33: sorting, recursion, backtracking, DP Implement every sort once, subsets and permutations, coin change, LCS

At the end of each week, close the guide and redraw three diagrams from memory. If you can draw it, you understand it.

Best Free Resources to Pair With This Guide

All links checked in December 2026. “Best for” is an honest opinion, not a ranking anyone paid for.

Resource Type Best for Why
VisuAlgo Interactive animations Best pick for watching algorithms move Step through sorts, trees and graphs on your own input
Data Structure Visualizations (USF) Interactive animations Trees and heaps Simple, fast, covers AVL and red-black trees too
Python Tutor Code visualizer Best pick for debugging your own code Paste the code from any topic page and watch memory and pointers change
MIT 6.006 Introduction to Algorithms University course Best pick for theory Lectures, notes and problem sets with proofs
Algorithms, Part I (Princeton, Coursera) Video course Clear implementations Union-find, sorting and search trees taught carefully
Algorithms by Jeff Erickson Free textbook Recursion, DP and graphs in depth Rigorous but readable, free PDF
Open Data Structures Free textbook How structures are built Implementations and analysis for every classic structure
CP-Algorithms Reference site Best pick for advanced topics Segment trees, string algorithms, flows, number theory
Competitive Programmer’s Handbook Free PDF book Contest techniques Short chapters that match the CSES problem set
USACO Guide Structured curriculum Self-paced practice by level Topic pages with ordered problems
Big-O Cheat Sheet Reference Quick complexity lookups One page with common structures and sorts

Where to practice

Platform Best for Notes
LeetCode Best pick for interview practice Largest set of interview-style problems
NeetCode practice list Pattern-by-pattern practice Problems grouped the way this guide groups techniques
LeetCode Patterns Filtering problems by pattern Free list tagged by technique
CSES Problem Set Best pick for depth Classic algorithm problems, strict time limits
AtCoder Contests with clean problems Beginner contests are a gentle start
HackerRank Online assessment practice Many companies use similar platforms for screening
Exercism Learning a language Mentored exercises in many languages

FAQ

What is the best way to learn data structures and algorithms? Alternate between understanding and doing. Read one topic, trace it by hand, implement it without looking, then solve a few problems that use it. Watching videos without coding feels productive but rarely sticks.

Which programming language is best for DSA? Any language you know well. Python is used here because the code is short and close to pseudocode. Learn your language’s built-ins: in Python that means list, dict, set, collections.deque, heapq and bisect.

How long does it take to learn DSA? Covering the 33 topics here takes about four weeks at an hour a day. Getting fast at interview problems usually takes another one to three months of regular practice.

Do I need to know math? Basic algebra, logarithms (log2 of n is how many times you can halve n) and simple sums are enough for almost everything here.

What is the difference between a data structure and an algorithm? A data structure is a way to organize data (a heap, a hash table). An algorithm is a step-by-step procedure (Dijkstra, merge sort). Algorithms are usually fast because they use the right data structure.

Which sorting algorithm is the fastest? For general data, well-implemented O(n log n) sorts such as quicksort variants, merge sort and Timsort (Python’s sorted) win. For small or nearly sorted data, insertion sort is very fast. Counting or radix sort can beat O(n log n) when keys are small integers.

BFS or DFS: which should I use? BFS for the shortest path in an unweighted graph or anything ‘minimum number of steps’. DFS for exploring everything, detecting cycles, topological order and backtracking.

When is dynamic programming the right tool? When the problem asks for a count, a minimum or a maximum, and a brute-force recursion would solve the same subproblems again and again. Write that recursion first, then add memoization.

Segment tree or Fenwick tree? Fenwick tree for prefix sums with point updates: less code. Segment tree when you need min/max or other aggregates, or range updates with lazy propagation.

Do Mermaid diagrams render outside GitHub? GitHub, GitLab and many Markdown editors render them. Elsewhere, paste a block into the Mermaid Live Editor or read the Mermaid documentation.

Where to Go Next

Contributing

Pull requests are welcome. Please keep every entry accurate:

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

License

The code and the content in this repository are released under the MIT License.

More free resources

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