DSA Demo Examples

Runnable Go programs, one file each, grouped by roadmap phase. Every demo is commented line by line to explain the reasoning, prints its own results, and checks itself where possible. Run any file with go run <file>.go (Go 1.23 or newer); no module setup is needed.

How to use: open a demo with View, read the header comment (it states the problem and the idea), predict the output, then download and run it. Each lesson's Practice Lab suggests a modification to try. Demos are numbered in study order; later phases are added here as they are published.

Phase 1: Foundations

Specification and invariants, complexity by counting and by measurement, recursion and the call stack, and Go's built-in structures. Lessons: Thinking in Algorithms, Complexity Analysis, Recursion, Data Structures Map.

#DescriptionLink
1Find the maximum: specification, loop invariant, table of test casesView
2Two Sum three ways: brute force, sort + two pointers, hash map — verified and timedView
3Growth rates: operation counts for O(1) through O(2ⁿ)View
4Doubling experiment: measure O(n²) vs O(n) and extrapolateView
5Recursion trace: watch stack frames push and popView
6Fast power: divide and conquer, O(n) vs O(log n) calls, modular formView
7Tower of Hanoi: recursive leap of faith with independent move verificationView
8Recursion to iteration: explicit stack over a file tree, one million levels deepView
9Built-in structures: arrays, slices, maps, container/list, heap, ringView
10Choosing a structure: blocklist as slice, sorted slice, and map, timed per workloadView

Phase 2: Core Data Structures

Arrays and array techniques, linked lists, stacks and queues, hash tables, binary trees, and heaps — each built from scratch in Go and verified against a brute-force oracle or invariant check. Lessons: Arrays & Slices, Linked Lists, Stacks & Queues, Hash Tables, Binary Trees & BST, Heaps.

#DescriptionLink
11Slice operations: insert, delete, filter in place, rotate — by hand and with the slices packageView
12Two pointers: palindromes, pair sum, dedupe, merge, Dutch flag, max water vs brute forceView
13Sliding window: fixed and variable windows, longest unique substring, shortest sum rangeView
14Prefix sums: O(1) range queries, subarray-sum counting with a map, 2D sums, difference arraysView
15Generic singly linked list with head/tail, removal edge cases, and a range iteratorView
16List techniques: reversal, middle, Floyd cycle detection, remove n-th from end, merge, palindromeView
17Doubly linked list with a sentinel: O(1) move-to-front playlist with invariant checksView
18Stack applications: bracket matching, RPN evaluation, shunting-yard, undo/redoView
19Ring-buffer queue and deque vs the naive slice queue, with allocation countsView
20Monotonic stack and deque: next greater, histogram rectangle, window maximumView
21Hash map from scratch: FNV-1a, separate chaining, resizing, good vs bad hashView
22Hash set with linear probing and tombstones, measured under churnView
23Hashing patterns: counting, seen sets, grouping by canonical key, longest consecutive runView
24Tree traversals: pre/in/post-order recursive and iterative, level order, sideways printView
25Generic BST: insert, three-case delete, ceiling, range queries, shape vs heightView
26Subtree thinking: diameter, balance, path sum, LCA, mirror, serialize/deserializeView
27Binary heap from scratch: sift up/down, O(n) heapify, heapsort with random checksView
28container/heap: scheduler with heap.Fix, top-k, k-way merge, running medianView

Phase 3: Core Algorithms

Binary search and its variants, the classic sorting algorithms, graph traversal, and weighted graph algorithms, each checked against a brute-force or slower oracle on random inputs. Lessons: Searching, Sorting, Graph Traversal, Shortest Paths & MST.

#DescriptionLink
29Linear vs binary search: invariant, step-by-step trace, comparisons and timingsView
30Search bounds: first-true template, lower/upper bound, rotated arrays, peak findingView
31Binary search on the answer: integer square root, ship capacity, eating speed, cube rootView
32Bubble, selection, and insertion sort: comparisons, moves, adaptivity, stabilityView
33Merge sort: recursion trace, bottom-up version, inversion counting, timingsView
34Quicksort: Lomuto partition, random pivot, three-way partition, quickselectView
35Counting sort and LSD radix sort vs slices.SortView
36Sorting in Go: multi-key comparators with cmp.Or, stable sorts, index sorting, the a - b bugView
37Graph representations: edge list, adjacency matrix, adjacency list, implicit gridView
38BFS: shortest paths, path reconstruction, maze solver, multi-source BFSView
39DFS: recursive and iterative, components, directed cycles, bipartite check, islandsView
40Topological sort: Kahn and DFS postorder, cycle detection, critical path of a buildView
41Union-find with union by size and path compression vs the naive versionView
42Dijkstra with container/heap, route reconstruction, Floyd-Warshall oracle, negative-edge failureView
43Bellman-Ford: negative weights, negative-cycle extraction, currency arbitrageView
44A* vs Dijkstra on a grid: expanded cells drawn, admissible and weighted heuristicsView
45Minimum spanning tree: Kruskal and Prim vs brute force, 2,000-point complete graphView

Phase 4: Advanced Algorithms

Algorithm design techniques for optimization problems and the specialised structures behind them. Every demo checks its answers against brute force on random inputs. This section grows one lesson at a time.

Greedy Algorithms

Lesson: Greedy Algorithms.

#DescriptionLink
46Interval scheduling: activity selection vs three wrong rules, fewest rooms, merging, stabbing pointsView
47When greedy fails: coin systems, fractional vs 0/1 knapsack, a 1/2-approximationView
48Scheduling by exchange argument: Smith's rule, earliest deadline first, deadlines and profits with union-findView
49Huffman coding: tree building, encode and decode, optimality via Kraft's inequality, Shannon-Fano comparisonView

Dynamic Programming

Lesson: Dynamic Programming.

#DescriptionLink
50Memoization and tabulation: Fibonacci call counts, grid paths, cheapest path with route, house robberView
51Knapsack family: 0/1 knapsack, loop direction, coin change, combinations vs sequences, subset sumView
52Sequence DP: longest increasing subsequence (O(n log n)), LCS, diff, edit distance with scriptView
53Interval and partition DP: matrix chain, burst balloons, word break, palindrome cutsView
54Bitmask and state-machine DP: travelling salesman, assignment, stock trading with cooldownView

Backtracking

Lesson: Backtracking.

#DescriptionLink
55Backtracking template: subsets, permutations, duplicates, combination sum with pruning, parentheses, the aliasing bugView
56N-Queens (arrays and bit masks) and Sudoku: pruning, most-constrained-cell order, a puzzle that defeats brute forceView
57Word search, prefix pruning, letter combinations, palindrome partitions, walking every cell vs a bitmask DPView
58Branch and bound: graph colouring with symmetry breaking, knapsack with a fractional bound at capacity over 10^9View

Advanced Trees

Lesson: Advanced Trees.

#DescriptionLink
59AVL tree: rotations, the four imbalance cases, height bound from Fibonacci, sorted input vs a plain BSTView
60Treap: split and merge, k-th smallest, rank and range count, sequence mode (insert, delete, rotate at any index)View
61Trie: prefix counts, autocomplete, delete, wildcard search, and a binary trie for the largest XOR pairView
62Fenwick tree: prefix sums with updates, range add, k-th item, counting inversionsView
63Segment tree over any operation, lazy range add, descent search, and a sparse table for static minimumView

String Algorithms

Lesson: String Algorithms.

#DescriptionLink
64Pattern matching: naive, KMP with the prefix function, Z-function, Horspool, smallest period, comparison countsView
65Rolling and prefix hashes: Rabin-Karp, arithmetic modulo 2^61-1, longest repeated and common substring, O(1) palindrome testView
66Palindromes: expand around centers, Manacher's algorithm, counting, shortest palindrome by adding in frontView
67Suffix array by prefix doubling, Kasai LCP, pattern search, distinct substrings, longest repeated and common substringView
68Aho-Corasick automaton: fail and output links, many patterns in one pass, censoringView

Advanced Techniques

Lesson: Advanced Techniques.

#DescriptionLink
69Bit manipulation: lowest-bit identities, submask and Gray code enumeration, Gosper's hack, XOR puzzles, a bitset sieveView
70Randomized algorithms: biased vs Fisher-Yates shuffle, reservoir sampling, quickselect, Miller-Rabin, Freivalds' checkView
71Bloom filter and Count-Min sketch: sizing, measured error against theory, heavy hitters in a Zipf streamView
72HyperLogLog: distinct counts in 16 KB, accuracy against memory, merging sketches for unionsView

Production Structures

Lesson: Production Structures.

#DescriptionLink
73LRU cache: map plus doubly linked list, TTL with an injected clock, hit ratio against capacity, the scan problemView
74Rate limiters: fixed window, sliding log, sliding counter, token bucket, the boundary attackView
75Consistent hashing: ring with virtual nodes, keys moved on add and remove, balance, replicas, rendezvous hashingView
76Concurrent structures: mutex and atomic counters, sharded map, lock-free stack, worker pool, call collapsingView