Useful Algorithms
A toolbox of must-know algorithms — searching, sorting, and graph traversal — built up step by step so you can reproduce them from memory.
These aren’t tied to a single LeetCode problem — they’re the building blocks that show up across hundreds of them. Learn each one until you can type it out without thinking.
Binary Search
Halve the search space each step to find a value in a sorted array in O(log n).
Quick Sort
Partition around a pivot, then recurse on each side. Average O(n log n), in place.
Depth-First Search (DFS)
Explore a graph by diving as deep as possible before backtracking.
Breadth-First Search (BFS)
Explore a graph level by level with a queue — the basis for shortest paths on unweighted graphs.
Dijkstra's Shortest Path
Shortest paths from a source on a weighted graph with non-negative edges, using a min-heap.
Topological Sort (Kahn's Algorithm)
Order the nodes of a DAG so every edge points forward — great for dependency resolution.
Union-Find (Disjoint Set Union)
Track connected groups with near-constant-time merges and membership checks.
Merge Sort
Divide the array, sort each half, then merge — a stable O(n log n) sort.
Quickselect
Find the k-th smallest element in O(n) average time, reusing quicksort's partition.
Binary Search on the Boundary
Find the first/last position with lower- and upper-bound search — the variant everyone gets wrong.
Binary Heap (Priority Queue)
A min-heap on a slice: O(log n) push and pop via sift-up and sift-down.
Trie (Prefix Tree)
Store words by shared prefixes for fast insert and lookup.
Backtracking (Subsets)
The choose / explore / un-choose template behind subsets, permutations, and combinations.
Kadane's Algorithm (Maximum Subarray)
The classic intro to DP: the largest-sum contiguous subarray in one pass.
Fast (Binary) Exponentiation
Compute x^n in O(log n) by squaring the base and reading n's bits.
Bellman-Ford
Single-source shortest paths that also handle negative edges and detect negative cycles.
Kruskal's Minimum Spanning Tree
Greedily add the lightest edges, using union-find to skip the ones that form cycles.
Floyd-Warshall (All-Pairs Shortest Paths)
Shortest paths between every pair of nodes with three nested loops.