Adjacency listGraphs
A graph representation that stores, for each vertex, the list of its neighbours. It takes O(V + E) memory and is the usual choice for sparse graphs.
121 terms, each defined in one to three sentences, with the other names people use for them and links to the lessons, visualizers, collections and problems where they come up. Every term has its own anchor, so other pages can link straight to it.
A graph representation that stores, for each vertex, the list of its neighbours. It takes O(V + E) memory and is the usual choice for sparse graphs.
A V × V table whose cell (u, v) records whether, or with what weight, an edge goes from u to v. It answers edge queries in O(1) but needs O(V²) memory.
Lessons: Graph representations: edge list, adjacency matrix and adjacency list
See also: Graph · Adjacency list
Also called: amortized analysis · amortized time · amortized complexity
The cost of an operation averaged over any sequence of operations, so occasional expensive steps are paid for by many cheap ones. A dynamic array append is O(n) when the buffer grows but amortized O(1).
Lessons: Dynamic arrays: capacity, resizing and amortized append
Visualizers: Dynamic array
Collections: List<T> · std::vector<T>
See also: Dynamic array · Capacity
Cheatsheets: Big O and the cost of common operations
Also called: big integer · bigint · BigInteger
An integer type that grows to hold any value, limited only by memory. Python’s int is one; C# and Java offer BigInteger. Arithmetic cost grows with the number of digits.
Lessons: Euclid’s algorithm: GCD and LCM · Primes with the Sieve of Eratosthenes
See also: Integer overflow
Cheatsheets: Language gotchas for DSA
Also called: fixed array · static array
A fixed number of elements of one type stored contiguously, read or written by index in O(1). Inserting or deleting in the middle shifts every later element, so it costs O(n).
Also called: extra space
The extra memory an algorithm uses beyond its input, including buffers and the call stack. Merge sort on arrays needs O(n) auxiliary space; heap sort needs O(1).
Lessons: Merge sort: split, merge and the auxiliary buffer
See also: Space complexity · In-place algorithm
Cheatsheets: Big O and the cost of common operations · Sorting algorithms
Also called: average-case complexity
The mean cost over a stated distribution of inputs of a given size. The answer depends entirely on that distribution, so it must be named.
Exploring a tree of decisions by choosing an option, recursing, and undoing the choice before trying the next. Pruning branches that cannot lead to a valid answer is what keeps it practical.
Lessons: Backtracking: subsets and permutations on a decision tree
See also: Recursion · Depth-first search
Cheatsheets: Pattern recognition
Also called: self-balancing tree · AVL tree · red-black tree · B-tree
A search tree that restructures itself, usually by rotations, to keep its height O(log n) after every insert and delete. AVL trees, red-black trees and B-trees are balanced; SortedDictionary, TreeMap and std::map are built on them.
Lessons: AVL trees and rotations, with red-black trees and B-trees
See also: Binary search tree
Cheatsheets: Big O and the cost of common operations
The input a recursive function answers directly, without recursing. Missing or unreachable base cases cause infinite recursion and, eventually, a stack overflow.
Lessons: Recursion and the call stack: base cases, frames and depth limits
See also: Recursion · Stack overflow
Also called: best-case complexity
The smallest cost over all inputs of a given size. It is rarely useful on its own, but it explains adaptive algorithms such as insertion sort, which is O(n) on sorted input.
Also called: big o · O notation · asymptotic upper bound
A way to state an upper bound on how a cost grows with input size, ignoring constant factors and lower-order terms. Saying an algorithm is O(n²) means its cost eventually stays below some constant times n².
Lessons: Counting operations and growth rates: O, Θ and Ω · Best, worst, average, expected and amortized cost · Space complexity, the call stack and multiple inputs
Complexity exercises: One loop over the input · A loop inside a loop
See also: Big Theta · Big Omega · Growth rate
Cheatsheets: Big O and the cost of common operations
Also called: Ω · omega notation · asymptotic lower bound
A lower bound on growth: the cost is at least a constant times the given function for large inputs. Every comparison sort is Ω(n log n) in the worst case.
Also called: Θ · theta notation · tight bound
A tight bound: the cost grows exactly as fast as the given function, up to constant factors, because it is both O and Ω of it. Merge sort is Θ(n log n) on every input.
Also called: half-interval search · bisection
Finding a target in a sorted range by comparing it with the middle element and discarding the half that cannot contain it. Each step halves the range, so it takes O(log n) comparisons.
Lessons: Binary search: halving a sorted range · Linear search and its preconditions · Jump, exponential and interpolation search · Binary search on the answer: the first true of a monotonic predicate
Visualizers: Binary search
Problems: Where does a value start and end? · Find the first broken build
See also: Lower bound (search) · Binary search on the answer · Logarithm
Cheatsheets: Pattern recognition
Also called: search on answer · parametric search · monotonic predicate search
Binary searching over possible answers instead of array positions, using a yes/no check that flips exactly once as the candidate grows. The cost is the check times the logarithm of the answer range.
Lessons: Binary search on the answer: the first true of a monotonic predicate
Problems: Find the first broken build
See also: Binary search
Cheatsheets: Pattern recognition
Also called: BST
A binary tree where every key in a node’s left subtree is smaller than the node’s key and every key in its right subtree is larger. Search, insert and delete take O(h), where h is the height, which degrades to O(n) when keys arrive in sorted order.
Also called: complete binary tree · full binary tree · perfect binary tree
A tree in which every node has at most two children, called left and right. A complete binary tree fills every level except possibly the last, from left to right, which is what lets a heap live in an array.
Lessons: Tree traversals: preorder, inorder, postorder and level order
Visualizers: Tree traversal
See also: Tree · Binary search tree · Heap (data structure)
Also called: mask · bit flags
An integer whose individual bits stand for yes/no flags or set membership. AND tests and clears bits, OR sets them, XOR toggles them, and shifts move them.
Also called: autoboxing · unboxing
Wrapping a primitive value in a heap object so it can be used where an object is expected, such as int in a Java List<Integer>. It costs memory and time, and comparing boxes with == in Java compares identity.
See also: Value type · Reference
Cheatsheets: Language gotchas for DSA
Also called: majority vote algorithm · voting algorithm
Finding an element that occurs more than half the time with one pass and O(1) memory, by pairing off different values against a running candidate. If no majority is guaranteed, a second pass must confirm the candidate.
Problems: Which candidate has more than half the votes?
Cheatsheets: Pattern recognition
Also called: BFS
Exploring a graph level by level from a start vertex using a queue, marking vertices when first seen. In an unweighted graph it finds shortest paths in edges, in O(V + E).
Lessons: BFS and DFS on graphs: queues, recursion and what each finds
Visualizers: Tree traversal · Queue (ring buffer)
See also: Queue · Depth-first search · Shortest path
Cheatsheets: Pattern recognition
Repeatedly swapping adjacent elements that are out of order, so each pass carries the largest remaining value to the end. It is stable and O(n²), or O(n) on sorted input with an early exit.
Lessons: Bubble, selection and insertion sort
Visualizers: Bubble sort
See also: Insertion sort · Stable sort
Cheatsheets: Sorting algorithms
Also called: locality of reference · spatial locality · temporal locality
The tendency of a program to reuse memory it touched recently or to touch nearby addresses next. Good locality lets the CPU cache serve most reads, so an array scan is far faster in practice than following linked-list pointers of the same Big O.
Also called: stack frame · execution stack · stack (memory)
The region of memory that holds one frame per active function call, with its parameters, locals and return address. Recursion deepens it, and running out of it is a stack overflow.
Lessons: Values, references and pointers · The call stack and the heap · Contiguous storage, addresses and cache locality · Reallocation and invalidated references · Reachability, garbage collection and RAII · Recursion and the call stack: base cases, frames and depth limits
Visualizers: Merge sort · Tree traversal
See also: Recursion · Stack overflow · Heap (memory)
Also called: buffer capacity
The number of elements a dynamic array’s buffer can hold before it must grow, as opposed to its size or count, the number actually stored. Reserving capacity up front avoids repeated reallocations.
Lessons: Dynamic arrays: capacity, resizing and amortized append
Visualizers: Dynamic array
Collections: std::vector<T> · ArrayList<E>
See also: Dynamic array · Reallocation
Also called: Unicode scalar value · rune
A number that Unicode assigns to one abstract character, written like U+00E9. Python strings index by code point, while UTF-16 needs two code units for code points above U+FFFF.
Also called: UTF-16 code unit · char
The fixed-size unit an encoding stores: 16 bits in UTF-16, 8 bits in UTF-8. C# and Java char values and string lengths count UTF-16 code units, so one emoji counts as two.
Also called: comparison function · IComparer · key function
A function or object that defines the order of two elements for sorting and ordered collections. Python usually takes a key function instead; C# uses IComparer<T> or a Comparison<T> delegate.
Lessons: Choosing a collection in C#, Python, Java and C++ · Iterators, equality and hashing contracts · Sorted collections and priority queues
Collections: PriorityQueue<E> · List<T>
See also: Strict weak ordering · Stable sort
Cheatsheets: Sorting algorithms
Also called: comparison-based sorting
A sort that learns about the order only by comparing pairs of elements. Any such sort needs Ω(n log n) comparisons in the worst case, a bound counting and radix sort escape by reading key values.
Also called: contiguous storage
A block of adjacent memory addresses with no gaps. Arrays store elements this way, which is why the address of element i can be computed directly and why scanning them is cache-friendly.
Lessons: Array layout and indexing · Values, references and pointers · The call stack and the heap · Contiguous storage, addresses and cache locality · Reallocation and invalidated references · Reachability, garbage collection and RAII · Traversal and linear search · Insert and delete in a fixed array · Dynamic arrays: capacity, resizing and amortized append · Multidimensional and jagged arrays
See also: Array · Cache locality
Sorting integer keys from a small range by counting how often each value occurs and placing elements by prefix sums of the counts. It runs in O(n + k) for a range of size k and is stable.
Also called: DFS
Exploring a graph by following one path as deep as possible before backing up, with recursion or an explicit stack. It runs in O(V + E) and underlies cycle detection, topological sort and connected components.
Lessons: BFS and DFS on graphs: queues, recursion and what each finds
Visualizers: Tree traversal
See also: Breadth-first search · Backtracking · Topological sort
Cheatsheets: Pattern recognition
Also called: double-ended queue · ArrayDeque
A double-ended queue that adds and removes at both ends in O(1). It can act as a stack, a queue, or the monotonic deque behind sliding-window maximums.
Lessons: Queues: first in, first out in a ring buffer
Collections: collections.deque · ArrayDeque<E> · std::deque<T>
See also: Queue · Monotonic deque
Cheatsheets: Collections across C#, Python, Java and C++
An array storing the change between neighbouring values, so adding a constant to a whole range touches only two entries. A prefix sum over it rebuilds the final values.
Lessons: Prefix sums and difference arrays
See also: Prefix sum
Also called: Dijkstra
Finding shortest paths from one vertex in a graph with non-negative edge weights by repeatedly settling the closest unsettled vertex, using a priority queue. With a binary heap it runs in O((V + E) log V).
Lessons: Dijkstra’s algorithm with a binary heap
See also: Shortest path · Priority queue
Cheatsheets: Pattern recognition
Splitting a problem into independent subproblems, solving them recursively, and combining the results. Merge sort, quicksort and binary search follow this shape, and recurrences describe their cost.
Lessons: Divide and conquer: recurrences, the Master theorem and quickselect
Visualizers: Merge sort
See also: Recurrence relation · Master theorem · Merge sort
Also called: three-way partition · DNF partition
A three-way partition that sorts a sequence of three kinds of value in one pass with three pointers. It also makes quicksort robust when many keys are equal.
Problems: Red, white and blue in one pass
See also: Partitioning · Two pointers
Cheatsheets: Pattern recognition
Also called: resizable array · growable array · vector · ArrayList · List<T>
An array that grows by moving its elements into a larger buffer when it runs out of room, giving O(1) indexing and amortized O(1) appends. List<T>, Python list, ArrayList and std::vector are dynamic arrays.
Lessons: Dynamic arrays: capacity, resizing and amortized append
Visualizers: Dynamic array
Collections: List<T> · list · ArrayList<E> · std::vector<T>
Problems: Push the empty slots to the end
See also: Array · Capacity · Amortized cost
Cheatsheets: Collections across C#, Python, Java and C++
Also called: DP
Solving a problem by defining states, expressing each state’s answer through smaller states, and computing each state once. It applies when subproblems overlap and optimal answers are built from optimal sub-answers.
Also called: equals/hashCode contract · Equals and GetHashCode · __eq__ and __hash__
The rule that objects which compare equal must produce the same hash code, and that neither may change while the object is a key. Break it and hash maps silently lose entries.
Lessons: Hash tables: buckets, chaining and load factor · Open addressing: probing and tombstones
Collections: HashMap<K, V> · Dictionary<TKey, TValue>
See also: Hash function · Hash map
Cheatsheets: Language gotchas for DSA
Also called: GCD · Euclid
Computing the greatest common divisor by repeatedly replacing the pair (a, b) with (b, a mod b) until b is zero. It takes O(log min(a, b)) steps.
Lessons: Euclid’s algorithm: GCD and LCM · Primes with the Sieve of Eratosthenes
Problems: The largest tile that fits both walls
See also: Modular arithmetic
Also called: expected complexity · expected running time
The cost averaged over random choices the algorithm or data structure makes itself, such as a random pivot or a hash function, for every fixed input. Hash table lookups are expected O(1).
Visualizers: Hash table
See also: Average case · Hash map · Quicksort
Cheatsheets: Big O and the cost of common operations
Also called: tortoise and hare · Floyd’s cycle detection
Moving one pointer two steps for every step of another. In a linked list they meet only if there is a cycle, and when the fast one reaches the end the slow one is at the middle.
Lessons: Singly linked lists: nodes, head and tail · Two pointers: opposite ends and read/write
Visualizers: Singly linked list
See also: Linked list · Two pointers
Also called: GC · garbage collector
Automatic reclamation of heap objects that no live reference can reach any more. C#, Java and Python use it; C++ frees memory deterministically instead (RAII).
Also called: network
A set of vertices connected by edges, which may be directed or undirected and weighted or unweighted. Grids, road maps, dependencies and social networks are all graphs.
Also called: user-perceived character · text element
What a reader sees as one character, which may be several code points, such as a letter plus a combining accent or a flag emoji. No built-in length in the four languages counts these by default.
Lessons: Strings in memory: code units, code points and graphemes · Counting characters: frequency tables, anagrams and palindromes · String matching: naive search and Knuth–Morris–Pratt
Problems: Does the phrase read the same both ways?
See also: Code point · Code unit
Cheatsheets: Language gotchas for DSA
Also called: greedy
Building a solution by always taking the choice that looks best right now and never revisiting it. It is correct only when an argument, often an exchange argument, shows the local choice can always be extended to an optimal answer.
Lessons: Greedy algorithms: interval scheduling and merging intervals
Problems: Buy once, sell once, profit most · Two walls that hold the most water
See also: Dynamic programming · Minimum spanning tree
Cheatsheets: Pattern recognition
Also called: order of growth · complexity class · growth class
How fast a cost function increases with input size, grouped into classes such as constant, logarithmic, linear, n log n, quadratic and exponential. Two algorithms in different classes eventually differ by more than any constant factor.
Lessons: Counting operations and growth rates: O, Θ and Ω · Best, worst, average, expected and amortized cost · Space complexity, the call stack and multiple inputs
Complexity exercises: Halving until one is left · Three nested loops
See also: Big O notation · Logarithm
Cheatsheets: Big O and the cost of common operations
Also called: collision
Two different keys landing in the same bucket. Collisions are unavoidable; a table resolves them by chaining or probing, and too many of them push lookups toward O(n).
Lessons: Hash tables: buckets, chaining and load factor · Open addressing: probing and tombstones
Visualizers: Hash table
See also: Separate chaining · Open addressing · Load factor
Also called: hashing · hash code · GetHashCode · hashCode
A function that maps a key to an integer, used to pick a bucket in a hash table. Equal keys must hash equally, and a good function spreads different keys evenly so collisions stay rare.
Lessons: Hash tables: buckets, chaining and load factor · Open addressing: probing and tombstones
Visualizers: Hash table
See also: Hash collision · Equality and hashing contract
Also called: hashmap · hash table · dictionary · dict · associative array · unordered_map
A key-value collection that hashes each key to choose a bucket, giving expected O(1) insert, lookup and delete. It needs a good hash function and an equality that agrees with it.
Lessons: Hash tables: buckets, chaining and load factor · Open addressing: probing and tombstones
Visualizers: Hash table
Collections: Dictionary<TKey, TValue> · dict · HashMap<K, V> · std::unordered_map<Key, T>
Problems: Two readings that add up to a target · Same letters, different order? · How many stretches add up to k?
See also: Hash function · Hash collision · Load factor · Hash set
Cheatsheets: Collections across C#, Python, Java and C++
Also called: HashSet · unordered_set · set
A collection of unique elements stored by hash, answering "is x present?" in expected O(1). It is a hash map that keeps keys without values.
Lessons: Hash tables: buckets, chaining and load factor · Open addressing: probing and tombstones
Collections: HashSet<T> · set · HashSet<E> · std::unordered_set<Key>
Problems: Has any badge been scanned twice?
See also: Hash map
Cheatsheets: Collections across C#, Python, Java and C++
Also called: binary heap · min-heap · max-heap
A complete binary tree, usually stored in an array, where every parent is no larger than its children (min-heap) or no smaller (max-heap). The top is read in O(1), insert and remove-top take O(log n), and building from n items takes O(n).
Lessons: Heaps and priority queues · Heap sort
Collections: PriorityQueue<TElement, TPriority> · heapq · PriorityQueue<E> · std::priority_queue<T>
See also: Priority queue · Heap sort · Heap (memory) · Top-k selection
Cheatsheets: Language gotchas for DSA
Also called: free store · managed heap · dynamic memory
The pool of memory for allocations whose lifetime is not tied to a single function call, such as objects created with new. It has nothing to do with the heap data structure apart from the name.
Also called: heapsort
Building a max-heap in the array, then repeatedly swapping the top to the end and restoring the heap on the rest. It is O(n log n) in the worst case and in place, but not stable.
Lessons: Heaps and priority queues · Heap sort
See also: Heap (data structure) · Introsort
Cheatsheets: Sorting algorithms
Also called: string immutability
A string that cannot change after it is created; every "modification" builds a new one. Strings are immutable in C#, Java and Python, so appending in a loop copies repeatedly unless you use a builder.
Also called: in place
An algorithm that transforms its input using only a small, usually O(1) or O(log n), amount of extra memory. Heap sort and quicksort are in place; array merge sort is not.
Lessons: Stability and in-place sorting
Problems: Push the empty slots to the end · Shift the schedule by k days
See also: Auxiliary space
Cheatsheets: Sorting algorithms
Also called: problem size
The quantity, usually called n, that complexity is measured against: the number of elements, the number of bits, or vertices and edges for a graph. With two independent inputs, keep two variables such as n and m.
Complexity exercises: Nested loops over two different inputs · Sequential loops over two inputs
See also: Time complexity
Growing a sorted prefix by lifting the next element and shifting larger ones right until it fits. It is stable, in place, O(n²) in general and O(n) on nearly sorted input, which is why hybrid sorts use it for small ranges.
Lessons: Bubble, selection and insertion sort
Visualizers: Insertion sort
Cheatsheets: Sorting algorithms
Also called: overflow · wraparound
An arithmetic result that does not fit in the integer type. It wraps around silently in C# (unchecked) and Java, is undefined behaviour for signed types in C++, and cannot happen with Python’s int.
Lessons: Euclid’s algorithm: GCD and LCM · Primes with the Sieve of Eratosthenes
Problems: Where does a value start and end?
See also: Undefined behaviour · Arbitrary-precision integer · Two’s complement
Cheatsheets: Language gotchas for DSA
Also called: introspective sort
A hybrid that runs quicksort, switches to heap sort when recursion gets too deep, and finishes small ranges with insertion sort. It keeps quicksort’s speed with an O(n log n) worst case; .NET’s Array.Sort and common std::sort implementations use it.
Lessons: What built-in sorts actually do
Collections: List<T>
See also: Quicksort · Heap sort · Insertion sort
Cheatsheets: Sorting algorithms
Also called: enumerator · cursor
An object that walks a collection one element at a time without exposing its layout. C# calls it an enumerator, Python uses the iterator protocol with __next__, and C++ iterators also act as positions for algorithms.
Also called: invalidated iterator · ConcurrentModificationException · concurrent modification
When changing a container makes existing iterators, pointers or references into it unsafe to use. C++ leaves the result undefined, while C# and Java detect many cases and throw, and Python raises for dicts and sets but not lists.
Collections: std::vector<T> · ArrayList<E>
See also: Iterator · Reallocation
Cheatsheets: Language gotchas for DSA
Also called: Kadane · maximum subarray algorithm
Finding the maximum-sum contiguous subarray in one pass by tracking the best sum of a run ending at the current element. A run is restarted whenever extending it would be worse than starting fresh.
Problems: The best streak of daily profits
See also: Dynamic programming
Cheatsheets: Pattern recognition
Also called: sequential search
Checking elements one by one until the target is found or the input ends. It works on any sequence and costs O(n).
Also called: singly linked list · doubly linked list
A sequence of nodes where each node points to the next (and, in a doubly linked list, the previous). Inserting after a node you already hold is O(1), but reaching the i-th node takes O(i) and the scattered nodes hurt cache locality.
Lessons: Singly linked lists: nodes, head and tail
Visualizers: Singly linked list
See also: Pointer · Sentinel node · Fast and slow pointers
The number of stored entries divided by the number of buckets. Tables resize once it passes a threshold (0.75 by default in Java’s HashMap) to keep chains or probe sequences short.
Lessons: Hash tables: buckets, chaining and load factor · Open addressing: probing and tombstones
Visualizers: Hash table
Collections: HashMap<K, V>
See also: Rehashing · Hash collision
Also called: log n · log2
The number of times you can divide a value by a base before reaching 1; log₂ 1,000,000 is about 20. Algorithms that halve their problem each step, like binary search, take logarithmic time, and the base only changes a constant factor.
Visualizers: Binary search
Complexity exercises: Halving until one is left · Doubling a counter
See also: Binary search · Growth rate
Also called: bisect_left · std::lower_bound · upper bound (search) · first occurrence
The first position in a sorted range whose element is not less than the target, which is also where the target would be inserted. Upper bound is the first position whose element is greater than the target.
Lessons: Binary search: halving a sorted range · Binary search on the answer: the first true of a monotonic predicate
Visualizers: Binary search
Problems: Where does a value start and end?
See also: Binary search
A recipe for solving recurrences of the form T(n) = a·T(n/b) + f(n) by comparing f(n) with n raised to log_b a. It does not apply when subproblems shrink by subtraction or have unequal sizes.
Also called: top-down DP · memoisation
Caching the result of a function call by its arguments so repeated calls return immediately. Applied to a recursive solution, it is top-down dynamic programming and can turn exponential time into polynomial.
Lessons: Recursion and the call stack: base cases, frames and depth limits · From recursion to dynamic programming: Fibonacci three ways · 0/1 knapsack: a 2D table and its traceback
Problems: How many ways up the stairs?
Complexity exercises: Naive recursive Fibonacci
See also: Dynamic programming · Tabulation
Splitting the input in half, sorting each half recursively, and merging the two sorted halves. It is stable and Θ(n log n) on every input, and on arrays it needs an O(n) buffer.
Lessons: Merge sort: split, merge and the auxiliary buffer
Visualizers: Merge sort
Problems: Merge two sorted lists into the first one
See also: Divide and conquer · Stable sort · Timsort
Cheatsheets: Sorting algorithms
Also called: MST · Kruskal’s algorithm · Prim’s algorithm
A subset of edges that connects every vertex of a weighted, undirected graph with the least total weight and no cycles. Kruskal’s algorithm builds one with sorting and union–find; Prim’s grows one with a priority queue.
Lessons: Minimum spanning trees: cut and cycle properties, Kruskal and Prim
See also: Union–Find · Greedy algorithm · Priority queue
Cheatsheets: Pattern recognition
Also called: modulo · mod
Arithmetic on remainders after division by a fixed modulus, where sums and products can be reduced at every step. It keeps large results in range and drives ring buffers and hashing.
Lessons: Euclid’s algorithm: GCD and LCM · Primes with the Sieve of Eratosthenes
Problems: Shift the schedule by k days
See also: Ring buffer · Euclidean algorithm
Cheatsheets: Language gotchas for DSA
Also called: monotonic queue
A deque kept in sorted order whose front is always the best value in the current window. It gives every sliding-window maximum or minimum in O(n) total.
Also called: monotone stack
A stack kept in increasing or decreasing order by popping everything that would break the order before pushing. Each element is pushed and popped at most once, so finding every next greater element takes O(n).
Lessons: Stacks: last in, first out on the end of an array
Problems: How many days until it gets warmer?
See also: Stack (data structure) · Monotonic deque
Cheatsheets: Pattern recognition
Also called: probing · linear probing · closed hashing
A collision strategy that stores every entry in the table array itself and, on a collision, probes other slots in a fixed sequence until it finds a free one. Linear probing has excellent locality but suffers from clustering at high load.
Lessons: Hash tables: buckets, chaining and load factor · Open addressing: probing and tombstones
Collections: dict
See also: Hash collision · Separate chaining · Load factor
Also called: partition · Lomuto partition · Hoare partition
Rearranging a range so that elements satisfying a condition come before the rest, in one linear pass. Lomuto and Hoare partitions drive quicksort; the three-way Dutch national flag partition handles many equal keys.
Lessons: Quicksort and partitioning
Problems: Red, white and blue in one pass
See also: Quicksort · Dutch national flag partition
A variable holding a memory address, which can be dereferenced, compared and, in C++, moved with arithmetic. Linked structures are built from pointers or references between nodes.
Lessons: Values, references and pointers · The call stack and the heap · Contiguous storage, addresses and cache locality · Reallocation and invalidated references · Reachability, garbage collection and RAII · Singly linked lists: nodes, head and tail
Visualizers: Singly linked list
See also: Reference · Linked list
Also called: popcount · Hamming weight · bit count
The number of 1 bits in an integer. Clearing the lowest set bit with x & (x - 1) counts them in as many steps as there are 1 bits, and all four languages expose a built-in.
Also called: cumulative sum · running sum · prefix sums
An array whose i-th entry is the sum of the first i input values, built in one pass. Any range sum then costs O(1) as the difference of two prefix sums.
Lessons: Prefix sums and difference arrays
Problems: How many stretches add up to k? · Where do both sides weigh the same? · Every product but your own
See also: Difference array · Sliding window
Cheatsheets: Pattern recognition
Also called: PriorityQueue · priority_queue · heapq
An abstract collection that always hands out the element with the highest priority (or the lowest, depending on convention) next. It is almost always implemented as a binary heap.
Lessons: Heaps and priority queues · Heap sort
Collections: PriorityQueue<TElement, TPriority> · heapq · PriorityQueue<E> · std::priority_queue<T>
See also: Heap (data structure) · Dijkstra’s algorithm
Cheatsheets: Collections across C#, Python, Java and C++
Also called: FIFO · FIFO queue
A first-in, first-out collection: enqueue adds at the back, dequeue removes from the front, both in O(1) when built on a ring buffer or linked list. Breadth-first search processes vertices in queue order.
Lessons: Queues: first in, first out in a ring buffer
Visualizers: Queue (ring buffer)
Collections: Queue<T> · collections.deque
See also: Deque · Ring buffer · Breadth-first search
Cheatsheets: Collections across C#, Python, Java and C++
Also called: quick sort
Partitioning the input around a pivot so smaller elements come first, then sorting each side recursively. It averages O(n log n) and is fast in practice, but repeatedly bad pivots make it O(n²).
Lessons: Quicksort and partitioning
See also: Partitioning · Introsort · Divide and conquer
Cheatsheets: Sorting algorithms
Sorting fixed-width keys digit by digit, from the least significant digit, with a stable sort on each pass. With d digits in base b it takes O(d · (n + b)).
Also called: resource acquisition is initialization
Resource acquisition is initialization: a C++ idiom where an object acquires a resource in its constructor and releases it in its destructor. Containers such as std::vector free their buffers this way when they go out of scope.
Also called: compaction · slow and fast index
A same-direction two-pointer pattern where one index reads every element and the other marks where the next kept element is written. It filters or compacts an array in place in O(n).
Lessons: Two pointers: opposite ends and read/write
Problems: Push the empty slots to the end · Keep one copy of each sorted value · Run-length encode a word
See also: Two pointers · In-place algorithm
Cheatsheets: Pattern recognition
Also called: resizing · growth factor · buffer growth
Moving a container’s elements into a new, larger buffer when the old one is full. Growing by a constant factor keeps appends amortized O(1), but every reallocation can invalidate pointers and iterators into the old buffer.
Lessons: Dynamic arrays: capacity, resizing and amortized append
Visualizers: Dynamic array
See also: Capacity · Amortized cost · Iterator invalidation
Also called: recurrence
An equation that defines the cost of a recursive algorithm in terms of the cost of smaller calls, such as T(n) = 2T(n/2) + n for merge sort. Solving it gives the closed-form complexity.
Lessons: Recursion and the call stack: base cases, frames and depth limits · Divide and conquer: recurrences, the Master theorem and quickselect
Complexity exercises: Recursion that peels off one element · Naive recursive Fibonacci
See also: Master theorem · Divide and conquer
Cheatsheets: Big O and the cost of common operations
Also called: recursive function
Solving a problem by calling the same function on smaller instances until a base case is reached. Every pending call occupies a stack frame, so depth matters as much as the number of calls.
Lessons: Recursion and the call stack: base cases, frames and depth limits
Visualizers: Tree traversal
Complexity exercises: Recursion that peels off one element · Naive recursive Fibonacci
See also: Base case · Call stack · Tail recursion
Also called: object reference · reference type
A value that refers to an object stored elsewhere, so copying it copies the link, not the object. Two references to the same list see each other’s changes.
Also called: rehash
Allocating a larger bucket array and reinserting every entry, triggered when the load factor gets too high. A single rehash is O(n), but geometric growth keeps inserts amortized O(1).
Lessons: Hash tables: buckets, chaining and load factor · Open addressing: probing and tombstones
Visualizers: Hash table
See also: Load factor · Amortized cost
Also called: circular buffer · circular queue
A fixed array used as a circle: head and tail indices advance modulo the capacity, so a queue never has to shift elements. When it fills, it either rejects new items or grows into a larger ring.
Lessons: Queues: first in, first out in a ring buffer
Visualizers: Queue (ring buffer)
Collections: Queue<T>
See also: Queue · Modular arithmetic
Repeatedly finding the smallest remaining element and swapping it into the next position. It always makes Θ(n²) comparisons but at most n − 1 swaps, and the swapping version is not stable.
Lessons: Bubble, selection and insertion sort
See also: Bubble sort · Insertion sort
Cheatsheets: Sorting algorithms
Also called: dummy node · dummy head
A dummy node placed before the first element (or after the last) so that inserting or deleting at the ends needs no special case. It holds no real data.
Lessons: Singly linked lists: nodes, head and tail
See also: Linked list
Also called: chaining
A collision strategy where each bucket holds a small list (or tree) of all entries that hash there. Java’s HashMap chains and converts long chains into balanced trees.
Lessons: Hash tables: buckets, chaining and load factor · Open addressing: probing and tombstones
Visualizers: Hash table
Collections: HashMap<K, V>
See also: Hash collision · Open addressing
Also called: single-source shortest path · Bellman–Ford
A path between two vertices with the smallest total weight, or the fewest edges when unweighted. Which algorithm applies depends on the weights: BFS for none, Dijkstra for non-negative, Bellman–Ford when negative edges exist.
Lessons: Dijkstra’s algorithm with a binary heap
See also: Breadth-first search · Dijkstra’s algorithm
Also called: window technique
Maintaining a contiguous range and its summary while moving the range across the input, adding what enters and removing what leaves. Fixed windows keep a constant length; variable windows grow and shrink while a condition holds.
Lessons: Sliding window: fixed and variable windows
Problems: The busiest stretch of k hours · The longest stretch without a repeated letter
See also: Two pointers · Monotonic deque · Prefix sum
Cheatsheets: Pattern recognition
Also called: memory complexity
How much memory an algorithm needs as its input grows, counting the input or not depending on convention. Recursion depth counts, because every active call holds a stack frame.
Also called: stability · stable sorting
A sort that keeps elements with equal keys in their original relative order. Stability lets you sort by a secondary key first and a primary key second.
Lessons: Stability and in-place sorting
Visualizers: Merge sort · Insertion sort
See also: Merge sort · Timsort
Cheatsheets: Sorting algorithms
Also called: stack · LIFO · LIFO stack
A last-in, first-out collection: push adds on top, pop removes the most recent item, both in O(1). It models nested work such as function calls, undo history and matching brackets.
Lessons: Stacks: last in, first out on the end of an array
Visualizers: Stack
Collections: ArrayDeque<E>
Problems: Do the brackets close properly?
See also: Monotonic stack · Call stack · Queue
Also called: StackOverflowError · RecursionError · recursion limit
Running out of call-stack space, usually from recursion that is too deep or never reaches its base case. Python raises RecursionError at its recursion limit, Java throws StackOverflowError, and in C# the process ends.
Lessons: Recursion and the call stack: base cases, frames and depth limits
See also: Call stack · Recursion · Base case
Cheatsheets: Language gotchas for DSA
The properties a C++ comparison must have: irreflexive, transitive, and with "neither is less" behaving as an equivalence. Using <= breaks it and makes std::sort undefined behaviour.
See also: Comparator · Undefined behaviour
Cheatsheets: Sorting algorithms
Also called: StringBuilder · string join
A growable character buffer that appends in amortized O(1) and produces the final string once. StringBuilder in C# and Java and "".join(parts) in Python avoid the O(n²) cost of repeated concatenation.
Also called: bottom-up DP
Bottom-up dynamic programming: filling a table of states in an order where every dependency is already computed. It avoids recursion, and often only the last few rows need to be kept.
Also called: tail call
Recursion where the recursive call is the very last action, so nothing in the current frame is needed afterwards. Some compilers reuse the frame, but C#, Java and Python do not guarantee it, so deep tail recursion can still overflow.
Lessons: Recursion and the call stack: base cases, frames and depth limits
See also: Recursion · Stack overflow
Also called: running time · runtime complexity
How the number of basic steps an algorithm performs grows as its input grows. It is stated per case (best, average, worst) and usually in Big O notation.
Lessons: Counting operations and growth rates: O, Θ and Ω · Best, worst, average, expected and amortized cost · Space complexity, the call stack and multiple inputs
Complexity exercises: One loop over the input · Two loops one after the other
See also: Space complexity · Worst case
Cheatsheets: Big O and the cost of common operations
Also called: tim sort · powersort
A stable, adaptive merge sort that finds already-sorted runs, extends short ones with insertion sort, and merges them with a balancing policy. Python and Java’s object sorts use it; it is O(n) on sorted input and O(n log n) in the worst case.
Lessons: What built-in sorts actually do
Collections: list
See also: Merge sort · Insertion sort
Cheatsheets: Sorting algorithms
Also called: top k · k largest · quickselect
Finding the k largest (or smallest) items without fully sorting. A size-k heap does it in O(n log k); quickselect finds the k-th element in average O(n).
Lessons: Heaps and priority queues · Heap sort · Divide and conquer: recurrences, the Master theorem and quickselect
See also: Heap (data structure) · Partitioning
Cheatsheets: Pattern recognition
Also called: topological ordering · Kahn’s algorithm · toposort
An ordering of a directed acyclic graph’s vertices in which every edge points forward. Kahn’s algorithm repeatedly removes vertices with no incoming edges; if some remain, the graph has a cycle.
Lessons: Topological sort with Kahn’s algorithm and cycle detection
See also: Depth-first search · Graph
Cheatsheets: Pattern recognition
Also called: rooted tree
A connected, acyclic set of nodes with one root, where every other node has exactly one parent. Depth is the distance from the root; height is the longest path down to a leaf.
Lessons: Tree traversals: preorder, inorder, postorder and level order
Visualizers: Tree traversal
See also: Binary tree · Tree traversal
Also called: preorder · inorder · postorder · level order
Visiting every node of a tree in a fixed order: preorder (node before children), inorder (between left and right), postorder (after children) or level order (row by row). Each visits all n nodes in Θ(n).
Lessons: Tree traversals: preorder, inorder, postorder and level order
Visualizers: Tree traversal
See also: Depth-first search · Breadth-first search · Tree
Also called: prefix tree · digital tree
A tree that stores strings one character per edge, so all keys sharing a prefix share a path from the root. Lookup and prefix queries cost O(L) for a key of length L, regardless of how many keys are stored.
Lessons: Tries: insert, search, prefixes and delete
Cheatsheets: Pattern recognition
Also called: two-pointer technique
Walking two indices through a sequence, from both ends toward each other or in the same direction, so each step discards possibilities instead of checking every pair. It often turns O(n²) pair searches into O(n).
Lessons: Two pointers: opposite ends and read/write
Problems: Two prices that fit the budget exactly · Two walls that hold the most water · Does the phrase read the same both ways? · Merge two sorted lists into the first one
See also: Read/write pointers · Fast and slow pointers · Sliding window
Cheatsheets: Pattern recognition
Also called: twos complement · signed binary
The standard binary encoding of signed integers, where the highest bit has negative weight. It makes addition the same for signed and unsigned values and gives an n-bit type the range −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1.
Lessons: Bits, masks and two’s complement
Problems: Count the 1 bits
See also: Integer overflow · Bitmask
Also called: UB · undefined behavior
A C++ operation for which the standard places no requirement on the result, such as signed overflow, reading out of bounds or using an invalidated iterator. The program may appear to work, crash, or be optimised in surprising ways.
See also: Integer overflow · Iterator invalidation · Strict weak ordering
Cheatsheets: Language gotchas for DSA
Also called: disjoint set union · DSU · disjoint-set
A structure that tracks which elements belong to the same group, supporting find (which group?) and union (merge two groups). With union by rank and path compression, each operation costs nearly O(1) amortized.
Lessons: Disjoint sets: union by rank and path compression
See also: Minimum spanning tree · Graph
Cheatsheets: Pattern recognition
Also called: value semantics
A type whose variables hold the data itself, so assignment copies it. C# structs, Java primitives and most C++ types behave this way; Python has no value types, only references to objects.
Also called: worst-case complexity
The largest cost over all inputs of a given size. It is the safe bound to quote when inputs can be chosen by someone else.
Also called: exclusive or
Exclusive or: a bit is 1 when exactly one of the two input bits is 1. Since x XOR x is 0 and XOR is order-independent, XOR-ing a list cancels every value that appears twice.
Lessons: Bits, masks and two’s complement
Problems: The sock without a pair
See also: Bitmask
Cheatsheets: Pattern recognition
No terms match. Try a shorter word or another category.