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).

Searching 8 languages

Quick Sort

Partition around a pivot, then recurse on each side. Average O(n log n), in place.

Sorting 8 languages

Depth-First Search (DFS)

Explore a graph by diving as deep as possible before backtracking.

Graphs 8 languages

Breadth-First Search (BFS)

Explore a graph level by level with a queue — the basis for shortest paths on unweighted graphs.

Graphs 8 languages

Dijkstra's Shortest Path

Shortest paths from a source on a weighted graph with non-negative edges, using a min-heap.

Graphs 8 languages

Topological Sort (Kahn's Algorithm)

Order the nodes of a DAG so every edge points forward — great for dependency resolution.

Graphs 8 languages

Union-Find (Disjoint Set Union)

Track connected groups with near-constant-time merges and membership checks.

Graphs 8 languages

Merge Sort

Divide the array, sort each half, then merge — a stable O(n log n) sort.

Sorting 8 languages

Quickselect

Find the k-th smallest element in O(n) average time, reusing quicksort's partition.

Sorting 8 languages

Binary Search on the Boundary

Find the first/last position with lower- and upper-bound search — the variant everyone gets wrong.

Searching 8 languages

Binary Heap (Priority Queue)

A min-heap on a slice: O(log n) push and pop via sift-up and sift-down.

Data structures 8 languages

Trie (Prefix Tree)

Store words by shared prefixes for fast insert and lookup.

Data structures 8 languages

Backtracking (Subsets)

The choose / explore / un-choose template behind subsets, permutations, and combinations.

Backtracking 8 languages

Kadane's Algorithm (Maximum Subarray)

The classic intro to DP: the largest-sum contiguous subarray in one pass.

Dynamic programming 8 languages

Fast (Binary) Exponentiation

Compute x^n in O(log n) by squaring the base and reading n's bits.

Math 8 languages

Bellman-Ford

Single-source shortest paths that also handle negative edges and detect negative cycles.

Graphs 8 languages

Kruskal's Minimum Spanning Tree

Greedily add the lightest edges, using union-find to skip the ones that form cycles.

Graphs 8 languages

Floyd-Warshall (All-Pairs Shortest Paths)

Shortest paths between every pair of nodes with three nested loops.

Graphs 8 languages