Algorithm Atlas
242 algorithms and data structures, from linear search to red-black trees. Every one has a plain-English explanation and its complexity. Those marked Animated (168 so far) also play step by step with the data, pointers and result drawn out, and you can run them on your own input.
Linear Search
AnimatedCheck each element in turn until the target is found.
O(n)
Binary Search
AnimatedRepeatedly halve a sorted list by comparing with the middle.
O(log n)
Ternary Search
AnimatedSplit a sorted range in three and discard two thirds each step.
O(log₃ n)
Jump Search
AnimatedJump ahead in blocks of √n, then scan the one block that can hold the target.
O(√n)
Interpolation Search
AnimatedGuess the position from the value, like looking up a name in a phone book.
O(log log n) avg, O(n) worst
Exponential Search
AnimatedDouble an index until it passes the target, then binary search that range.
O(log i)
Fibonacci Search
AnimatedBinary-search variant that splits by Fibonacci numbers using only + and −.
O(log n)
Hash-based Search
AnimatedJump straight to a bucket computed from the key.
O(1) avg, O(n) worst
Bubble Sort
AnimatedSwap adjacent out-of-order pairs until none remain.
O(n²)
Selection Sort
AnimatedRepeatedly select the minimum and put it first.
O(n²)
Insertion Sort
AnimatedInsert each item into the already-sorted prefix.
O(n²), O(n) if sorted
Merge Sort
AnimatedSplit, sort halves, merge. Stable and predictable.
O(n log n)
Quick Sort
AnimatedPartition around a pivot, then sort each side.
O(n log n) avg, O(n²) worst
Heap Sort
AnimatedBuild a max-heap, then repeatedly extract the maximum.
O(n log n)
Counting Sort
AnimatedCount occurrences of each small integer, then rebuild the list.
O(n + k)
Radix Sort
AnimatedSort digit by digit with a stable sort.
O(d · (n + k))
Bucket Sort
AnimatedDistribute into range buckets, sort each, concatenate.
O(n) avg, O(n²) worst
Shell Sort
AnimatedInsertion sort over shrinking gaps.
About O(n^1.3) in practice
Tim Sort
Finds natural runs, extends them with insertion sort, then merges.
O(n log n), O(n) if sorted
Intro Sort
Quick sort that switches to heap sort if recursion gets too deep.
O(n log n)
Cycle Sort
AnimatedRotate items into place, writing each at most once.
O(n²)
Comb Sort
AnimatedBubble sort with a shrinking gap to kill "turtles".
About O(n²) worst
Cocktail Shaker Sort
AnimatedBubble sort that alternates direction each pass.
O(n²)
Pigeonhole Sort
AnimatedOne hole per possible value; drop items in and read back.
O(n + range)
Tree Sort
AnimatedInsert into a binary search tree, then read in-order.
O(n log n) avg, O(n²) worst
Bitonic Sort
A sorting network that builds bitonic sequences, then merges them.
O(log² n) parallel depth
Pancake Sort
AnimatedSort using only prefix reversals.
O(n²)
Bogosort
AnimatedShuffle until sorted. A joke algorithm that shows why efficiency matters.
O(n · n!) expected
Kadane's Algorithm (Maximum Subarray)
AnimatedTrack the best sum ending at each position; restart when it goes negative.
O(n)
Dutch National Flag Algorithm
AnimatedPartition an array into three groups in one pass with three pointers.
O(n)
Moore's Voting (Boyer–Moore Majority Vote)
AnimatedCancel out different elements in pairs; the survivor is the majority candidate.
O(n)
Two Pointer Technique
AnimatedMove two indexes towards each other (or together) instead of nesting loops.
O(n)
Sliding Window Technique
AnimatedSlide a fixed or growing window, updating its value incrementally.
O(n)
Prefix Sum
AnimatedStore running totals so any range sum is one subtraction.
O(n) build, O(1) query
Suffix Sum
AnimatedRunning totals from the right end.
O(n) build, O(1) query
Difference Array
AnimatedRecord range additions as two edits, then prefix-sum to apply them all.
O(1) update, O(n) rebuild
Maximum Product Subarray
AnimatedTrack both the largest and smallest product ending here (negatives flip them).
O(n)
Next Permutation
AnimatedFind the next arrangement in lexicographic order in place.
O(n)
Trapping Rain Water
AnimatedWater above a bar = min(left max, right max) − height; two pointers compute it.
O(n)
Stock Buy and Sell
AnimatedTrack the lowest price so far and the best profit.
O(n)
Leaders in an Array
AnimatedScan from the right keeping the maximum; each new maximum is a leader.
O(n)
Missing Number Algorithm
AnimatedExpected sum 0..n minus the actual sum (or XOR everything).
O(n)
Cyclic Sort
AnimatedPut each value at the index it belongs to by swapping.
O(n)
Fast and Slow Pointer Technique
AnimatedTwo pointers moving at different speeds reveal cycles and midpoints.
O(n)
Naive Pattern Matching
AnimatedSlide the pattern along the text and compare at every position.
O(n · m)
KMP Algorithm
AnimatedUse a failure table so the text pointer never moves backwards.
O(n + m)
Rabin–Karp Algorithm
AnimatedCompare rolling hashes of windows, verifying only on a hash match.
O(n + m) avg, O(n · m) worst
Z Algorithm
AnimatedFor each position, the length of the longest match with the string start.
O(n)
Boyer–Moore String Search
AnimatedCompare from the pattern end and skip ahead using mismatch rules.
O(n/m) best, O(n · m) worst
Manacher's Algorithm
Find every palindromic radius in linear time by reusing mirrored results.
O(n)
Aho–Corasick Algorithm
A trie with failure links that matches many patterns in one pass.
O(n + m + z)
Suffix Array
The sorted list of all suffixes of a string.
O(n log n) build
Suffix Tree
A compressed trie of all suffixes.
O(n) build (Ukkonen)
Longest Common Prefix
AnimatedCompare strings column by column until a mismatch.
O(n · m)
Longest Palindromic Substring
AnimatedExpand outwards from every centre.
O(n²)
Trie-based String Search
Follow one edge per character in a prefix tree.
O(m)
Rolling Hash
AnimatedUpdate a window hash by removing the old character and adding the new one.
O(1) per slide
Floyd's Cycle Detection
AnimatedA slow and a fast pointer meet if and only if there is a cycle.
O(n)
Reverse a Linked List
AnimatedFlip each next pointer while walking the list.
O(n)
Merge Two Sorted Linked Lists
AnimatedRepeatedly attach the smaller head to the result.
O(n + m)
Detect and Remove Loop
AnimatedFind the cycle start with Floyd, then cut the last node.
O(n)
Find Middle of Linked List
AnimatedWhen the fast pointer reaches the end the slow one is at the middle.
O(n)
Find Nth Node from End
AnimatedStart two pointers n apart and move them together.
O(n)
Intersection of Two Linked Lists
Walk both lists, switching heads at the end, so the pointers meet at the intersection.
O(n + m)
Palindrome Linked List
AnimatedReverse the second half and compare it with the first.
O(n)
Flatten a Multilevel Linked List
Splice each child list into the main list after its parent.
O(n)
Merge Sort on Linked List
Split with slow/fast pointers, sort halves, merge.
O(n log n)
Reorder List
Interleave the first half with the reversed second half.
O(n)
Rotate Linked List
AnimatedConnect the tail to the head and cut at the new tail.
O(n)
Next Greater Element
AnimatedA stack of waiting items resolves each when a bigger one arrives.
O(n)
Next Smaller Element
AnimatedSame idea with the comparison reversed.
O(n)
Previous Greater Element
AnimatedScan left to right, keeping a stack of candidates.
O(n)
Previous Smaller Element
AnimatedScan left to right with an increasing stack.
O(n)
Monotonic Stack
AnimatedA stack kept in sorted order by popping items that break the order.
O(n)
Monotonic Queue
A deque kept sorted so its front is the window maximum or minimum.
O(n)
Largest Rectangle in Histogram
AnimatedA monotonic stack finds how far each bar can extend.
O(n)
Sliding Window Maximum
AnimatedA decreasing deque keeps the maximum at its front.
O(n)
Stock Span Problem
AnimatedCount consecutive earlier days with price ≤ today using a stack.
O(n)
Valid Parentheses
AnimatedPush openers, pop on closers, and check they match.
O(n)
Infix to Postfix Conversion
AnimatedShunting-yard: an operator stack orders operators by precedence.
O(n)
Infix to Prefix Conversion
Reverse, convert to postfix with swapped brackets, reverse again.
O(n)
Postfix Evaluation
AnimatedPush numbers; each operator pops two and pushes the result.
O(n)
Queue Using Stacks
AnimatedAn input stack and an output stack reverse the order twice.
O(1) amortised
Stack Using Queues
After each push, rotate the queue so the newest item is at the front.
O(n) push or pop
Min Stack
AnimatedKeep a second stack of running minimums.
O(1)
LRU Cache
AnimatedA hash map plus a recency list evicts the least recently used item.
O(1) get and put
Inorder Traversal
AnimatedLeft, node, right. On a BST this yields sorted order.
O(n)
Preorder Traversal
AnimatedNode, left, right. Visits parents before children.
O(n)
Postorder Traversal
AnimatedLeft, right, node. Visits children before parents.
O(n)
Level Order Traversal
AnimatedVisit the tree row by row using a queue.
O(n)
Zigzag Traversal
AnimatedLevel order that reverses direction on alternate rows.
O(n)
Morris Traversal
Temporarily link predecessors to walk the tree without a stack.
O(n)
Binary Search Tree Search
AnimatedGo left or right by comparing with each node.
O(h)
BST Insertion
AnimatedWalk down as in search and attach a new leaf.
O(h)
BST Deletion
AnimatedRemove a leaf, bypass a single child, or replace with the in-order successor.
O(h)
Lowest Common Ancestor (LCA)
AnimatedThe deepest node that has both targets in its subtree.
O(h)
Diameter of Binary Tree
AnimatedThe longest path is max over nodes of left height + right height.
O(n)
Height of Binary Tree
Animated1 + the larger height of the two children.
O(n)
Balanced Binary Tree
Check at every node that child heights differ by at most 1.
O(n)
Boundary Traversal
Left edge, then leaves, then right edge going up.
O(n)
Vertical Order Traversal
Group nodes by horizontal distance from the root.
O(n log n)
Top View
The first node seen at each horizontal distance from above.
O(n)
Bottom View
The last node seen at each horizontal distance.
O(n)
Serialize and Deserialize Binary Tree
Write the tree with null markers, then rebuild it from the text.
O(n)
Construct Tree from Traversals
Preorder gives roots; inorder splits left from right.
O(n)
Tree Flattening
Rewire a tree into a right-leaning linked list in preorder.
O(n)
Depth-First Search (DFS)
AnimatedGo as deep as possible, then backtrack.
O(V + E)
Breadth-First Search (BFS)
AnimatedExplore level by level with a queue.
O(V + E)
Dijkstra's Algorithm
AnimatedAlways settle the closest unsettled node.
O((V + E) log V)
Bellman–Ford Algorithm
AnimatedRelax every edge V−1 times; one more pass detects negative cycles.
O(V · E)
Floyd–Warshall Algorithm
AnimatedTry every node as an intermediate stop for every pair.
O(V³)
Johnson's Algorithm
Reweight edges with Bellman–Ford, then run Dijkstra from every node.
O(V² log V + V · E)
Prim's Algorithm
AnimatedGrow a spanning tree by always adding the cheapest edge leaving it.
O(E log V)
Kruskal's Algorithm
AnimatedAdd edges cheapest first unless they form a cycle (union-find).
O(E log E)
Minimum Spanning Tree
AnimatedThe cheapest set of edges that connects every node. Built by Prim or Kruskal.
O(E log V)
Topological Sorting
AnimatedOrder a DAG so every edge points forward.
O(V + E)
Kahn's Algorithm
AnimatedRepeatedly remove nodes with no incoming edges.
O(V + E)
Kosaraju's Algorithm
DFS finish order, then DFS on the reversed graph finds each SCC.
O(V + E)
Tarjan's Algorithm
One DFS with low-link values and a stack finds all SCCs.
O(V + E)
Strongly Connected Components
Maximal groups of nodes that can all reach each other.
O(V + E)
Cycle Detection
AnimatedDFS finds a back edge to an ancestor.
O(V + E)
Union-Find (Disjoint Set Union)
AnimatedTrack groups with parent pointers, path compression and union by rank.
O(α(n)) per op
Bridges in Graph
Edges whose removal disconnects the graph, found with DFS low-links.
O(V + E)
Articulation Points
Nodes whose removal disconnects the graph.
O(V + E)
Eulerian Path Algorithm
A path that uses every edge exactly once; exists if 0 or 2 nodes have odd degree.
O(V + E)
Hierholzer's Algorithm
Build an Euler circuit by splicing together cycles.
O(E)
Hamiltonian Path
A path that visits every node exactly once. NP-complete.
O(n!) brute force, O(2ⁿ · n²) DP
A* Search Algorithm
Dijkstra guided by a heuristic estimate of the remaining distance.
O(E) with a good heuristic
Bidirectional BFS
Search from both ends at once and stop when they meet.
O(b^(d/2))
0-1 BFS
BFS with a deque: 0-weight edges to the front, 1-weight to the back.
O(V + E)
Multi-source BFS
Start the queue with several sources at once.
O(V + E)
Fibonacci DP
AnimatedEach number is the sum of the previous two; remember them instead of recomputing.
O(n)
Climbing Stairs
AnimatedWays to reach step n = ways(n−1) + ways(n−2).
O(n)
0/1 Knapsack
AnimatedFor each item choose take or skip to maximise value within capacity.
O(n · W)
Unbounded Knapsack
AnimatedLike 0/1 knapsack but each item can be used unlimited times.
O(n · W)
Fractional Knapsack
AnimatedTake items by best value per weight, splitting the last one.
O(n log n)
Coin Change
AnimatedFewest coins for an amount: best of (coins for amount − c) + 1.
O(n · amount)
Longest Common Subsequence (LCS)
AnimatedA table of the longest common subsequence of every pair of prefixes.
O(n · m)
Longest Increasing Subsequence (LIS)
AnimatedLongest subsequence in strictly increasing order.
O(n²), O(n log n) with patience
Longest Common Substring
AnimatedLike LCS but the match must be contiguous.
O(n · m)
Edit Distance
AnimatedFewest insertions, deletions and substitutions to turn one string into another.
O(n · m)
Levenshtein Distance
AnimatedEdit distance with unit costs. Same algorithm as edit distance.
O(n · m)
Matrix Chain Multiplication
Choose the bracketing that minimises scalar multiplications.
O(n³)
Subset Sum
AnimatedCan some subset add up to the target?
O(n · target)
Partition Equal Subset Sum
AnimatedSplit into two equal-sum halves: subset sum with target sum/2.
O(n · sum)
Rod Cutting
AnimatedBest revenue from cutting a rod into priced pieces.
O(n²)
Egg Dropping
Fewest drops that guarantee finding the critical floor.
O(k · n²)
Palindrome Partitioning
Fewest cuts so every piece is a palindrome.
O(n²)
Word Break
AnimatedCan the string be split into dictionary words?
O(n²)
House Robber
AnimatedMax loot without taking two adjacent houses.
O(n)
Maximum Path Sum
Best path in a tree or triangle by combining best child paths.
O(n)
Unique Paths
AnimatedPaths in a grid moving right or down = paths from above + paths from the left.
O(m · n)
Minimum Path Sum
AnimatedCheapest grid path moving right or down.
O(m · n)
Wildcard Matching
Match with ? (any char) and * (any run) using a table.
O(n · m)
Regular Expression Matching
Match with . and * by building on smaller prefixes.
O(n · m)
Bitmask DP
Encode which items are used as bits in an integer state.
O(2ⁿ · n)
Digit DP
Count numbers with a property by building them digit by digit.
O(digits · states)
Tree DP
Compute each node’s answer from its children’s answers.
O(n)
Interval DP
Solve every sub-interval, then combine them into larger ones.
O(n³)
DP on Graphs
Run DP over a DAG in topological order.
O(V + E)
State Compression DP
Pack a large state into a small integer.
O(2ⁿ · n)
Travelling Salesman Problem (DP)
Held–Karp: best tour over every subset of visited cities.
O(2ⁿ · n²)
Activity Selection
AnimatedSort by finish time; take each activity that starts after the last one ends.
O(n log n)
Job Sequencing with Deadlines
AnimatedDo the highest-profit jobs, each in the latest free slot before its deadline.
O(n log n)
Huffman Coding
AnimatedRepeatedly merge the two rarest symbols into a tree to get optimal prefix codes.
O(n log n)
Minimum Platforms
AnimatedSort arrivals and departures; track the most trains present at once.
O(n log n)
Gas Station Problem
AnimatedIf the tank goes negative, restart after that station.
O(n)
Jump Game
AnimatedTrack the furthest reachable index.
O(n)
Candy Distribution
Two passes make each child get more than a lower-rated neighbour.
O(n)
Meeting Rooms
AnimatedSort and sweep to find how many rooms are needed.
O(n log n)
Interval Scheduling
AnimatedPick the interval that finishes earliest.
O(n log n)
Interval Partitioning
AnimatedAssign each interval to a free resource, opening a new one only if needed.
O(n log n)
Minimum Coin Change (Greedy)
AnimatedAlways take the largest coin that fits. Optimal only for canonical coin systems.
O(n)
Optimal Merge Pattern
Always merge the two smallest files.
O(n log n)
Egyptian Fraction
Repeatedly subtract the largest unit fraction.
O(log n) terms
Assign Cookies
AnimatedGive the smallest sufficient cookie to the least greedy child.
O(n log n)
Non-overlapping Intervals
AnimatedRemove the fewest intervals by keeping those that end earliest.
O(n log n)
N-Queens Problem
AnimatedPlace queens row by row, backing up when a square is attacked.
O(n!)
Sudoku Solver
Fill cells with legal digits, undoing wrong guesses.
O(9^empty)
Rat in a Maze
AnimatedExplore moves, mark visited cells, and unmark on dead ends.
O(4^(n²))
Knight's Tour
Visit every square once with knight moves.
O(8^(n²))
Subset Generation
AnimatedFor each item choose include or exclude.
O(2ⁿ · n)
Permutation Generation
AnimatedBuild arrangements by choosing an unused item at each position.
O(n! · n)
Combination Sum
AnimatedChoose numbers that add up to a target, allowing reuse.
Exponential
Word Search
DFS from each cell, marking letters used.
O(m · n · 4^L)
Graph Coloring
AnimatedGive adjacent nodes different colours using at most m colours.
O(mⁿ)
Hamiltonian Cycle
AnimatedFind a cycle through every node once by extending a path and backing up.
O(n!)
M-Coloring Problem
AnimatedDecide whether a graph can be coloured with m colours.
O(mⁿ)
Generate Parentheses
AnimatedAdd "(" while fewer than n are used, and ")" while it would stay balanced.
O(4ⁿ / √n)
Letter Combinations of a Phone Number
AnimatedChoose one letter for each digit.
O(4ⁿ)
Crossword Puzzle Solver
Place words in slots and undo conflicts.
Exponential
Closest Pair of Points
Split by x, solve each half, check the strip near the dividing line.
O(n log n)
Strassen's Matrix Multiplication
Multiply 2×2 blocks with 7 products instead of 8.
O(n^2.81)
Karatsuba Multiplication
AnimatedMultiply big numbers with 3 half-size products instead of 4.
O(n^1.585)
Count Inversions
AnimatedCount while merge sorting: items jumping over larger ones.
O(n log n)
Quick Select
AnimatedQuick sort that only recurses into the side holding the k-th item.
O(n) avg, O(n²) worst
Median of Two Sorted Arrays
AnimatedBinary search the partition between the arrays.
O(log(min(n, m)))
Brian Kernighan's Algorithm
Animatedn & (n−1) clears the lowest set bit; count how many times you can do it.
O(set bits)
Bitmasking
AnimatedStore a set of flags in the bits of an integer.
O(1) per op
XOR-based Algorithms
Animateda ^ a = 0 and a ^ 0 = a, so pairs cancel out.
O(n)
Count Set Bits
AnimatedCount the 1s in the binary form of a number.
O(log n)
Check Power of Two
AnimatedA positive n is a power of two iff n & (n−1) == 0.
O(1)
Find Single Non-Repeating Element
AnimatedXOR every number; pairs cancel and the single one remains.
O(n)
Find Two Non-Repeating Elements
AnimatedXOR all, split the numbers by a differing bit, and XOR each group.
O(n)
Subset Generation Using Bits
AnimatedEach number from 0 to 2ⁿ−1 is a subset mask.
O(2ⁿ · n)
Bitwise Sieve
Sieve of Eratosthenes storing one bit per number.
O(n log log n)
Gray Code Generation
AnimatedSequence where neighbours differ by one bit: g = i ^ (i >> 1).
O(2ⁿ)
Fast Exponentiation
AnimatedSquare the base and halve the exponent.
O(log n)
Binary Exponentiation
AnimatedUse the binary digits of the exponent to multiply selectively.
O(log n)
Euclidean Algorithm
Animatedgcd(a, b) = gcd(b, a mod b).
O(log min(a, b))
GCD
AnimatedThe largest number that divides both inputs.
O(log min(a, b))
LCM
Animatedlcm(a, b) = a / gcd(a, b) · b.
O(log min(a, b))
Extended Euclidean Algorithm
AnimatedFinds x, y with ax + by = gcd(a, b).
O(log min(a, b))
Sieve of Eratosthenes
AnimatedCross out multiples of each prime.
O(n log log n)
Segmented Sieve
Sieve a range in blocks using primes up to √n.
O(n log log n)
Sieve of Sundaram
Remove numbers i + j + 2ij; the rest give odd primes.
O(n log n)
Prime Factorisation
AnimatedDivide out each prime factor by trial division.
O(√n)
Modular Arithmetic
Arithmetic that wraps around a modulus.
O(1) per op
Modular Exponentiation
AnimatedCompute b^e mod m by repeated squaring, reducing as you go.
O(log e)
Fermat's Little Theorem
Animateda^(p−1) ≡ 1 (mod p) for prime p, so a⁻¹ = a^(p−2).
O(log p)
Euler's Totient Function
AnimatedCount of numbers ≤ n that are coprime to n.
O(√n)
Chinese Remainder Theorem
AnimatedCombine congruences with coprime moduli into one.
O(k log m)
Fast Doubling Fibonacci
AnimatedCompute F(2k) and F(2k+1) from F(k) and F(k+1).
O(log n)
Catalan Numbers
AnimatedC(n) counts balanced brackets, binary trees and more.
O(n²) DP, O(n) formula
Segment Tree
AnimatedA tree where each node stores a summary of a range.
O(log n) query/update
Lazy Propagation
AnimatedDelay range updates in the tree until they are needed.
O(log n) range update
Fenwick Tree (Binary Indexed Tree)
AnimatedPrefix sums using clever binary-indexed partial sums.
O(log n)
Sparse Table
AnimatedPrecompute answers for ranges of power-of-two lengths.
O(n log n) build, O(1) query
Trie
AnimatedA tree where each edge is a character.
O(m) per operation
Suffix Automaton
The smallest automaton accepting all suffixes of a string.
O(n)
Heavy-Light Decomposition
Split a tree into heavy chains so paths become few array ranges.
O(log² n) path query
Centroid Decomposition
Recursively remove the centroid to get a log-depth tree.
O(n log n)
Mo's Algorithm
Answer offline range queries by sorting them to minimise pointer movement.
O((n + q) √n)
Persistent Segment Tree
Keep every past version by copying only the changed path.
O(log n) per version
Treap
A BST ordered by key and a heap ordered by random priority.
O(log n) expected
AVL Tree
AnimatedA BST that rotates to keep child heights within 1.
O(log n)
Red-Black Tree
A BST balanced with colour rules and fewer rotations.
O(log n)
B-Tree
A wide, shallow balanced tree with many keys per node.
O(log n)
B+ Tree
A B-tree storing all data in linked leaves.
O(log n)
K-D Tree
A binary tree that splits space along alternating axes.
O(log n) avg search
Bloom Filter
AnimatedA bit array and several hashes that answer "definitely not" or "probably yes".
O(k) per op
Skip List
A linked list with random express lanes.
O(log n) expected