Algorithm design 2026-10-31
Constructing an algorithm that meets a stated specification. Choices such as divide-and-conquer algorithms, dynamic programming and greedy algorithms organize the construction; an algorithm correctness argument establishes that the result meets the specification.
Alignment traceback 2026-10-31
Store a maximizing predecessor at each dynamic programming table entry. A diagonal predecessor emits a pair of letters; a vertical or horizontal predecessor emits a letter opposite a gap. Construct the columns in reverse and then reverse the output. For global sequence alignment without mismatches, start at the full-prefix entry and stop at the origin. For local sequence alignment without mismatches, start at any largest entry and stop at a zero entry. Each move decreases a prefix index, so at most moves are needed after the table is built.
Here counts increasing position embeddings of the word as a subsequence of . Counting embeddings retains repeated-letter multiplicities. The empty word has one embedding in every string. Prefix dynamic programming computes this positive-semidefinite kernel by with boundary values one. The time complexity is arithmetic operations, and rolling rows require integer cells. Counting pairs of position subsets bounds output bit length by .
Keep the original all-to-one orientation of the Bellman inequalities: concerns routes from to a fixed sink , and belongs to the original directed edge . Initialize and for . The synchronous dynamic programming recurrence is
It prepends the first edge of a route instead of appending the last: is the minimum cost of a directed walk from to using at most edges. In particular, improving can improve labels on incoming directed edges . The same original directed edge therefore updates its tail in this convention, whereas single-source edge relaxation updates its head.
If no negative-cost directed cycle can reach , rounds suffice for every distance to , and automatically. This hypothesis concerns directed paths from the cycle to the sink, not paths from the sink to the cycle. In the base example with its original arrows and sink , the distances in order are . Once of weight is added, instead have distance to , while keeps distance and keeps .
More generally, precisely when can reach a negative-cost directed cycle that can reach . Thus the affected vertices are the ancestors of such a directed cycle. A negative-cost directed cycle unable to reach is irrelevant. Reversing all arrows makes a single source, turns these ancestors into descendants, and makes the detection and forward graph search above directly applicable. The right panel of the figure uses that reversal with sink ; its distances to equal the left panel's distances from .
Do not force the root to remain zero outside the hypothesis. Consider the two directed edges of cost and of cost , with sink . The recurrence gives and : the latter records one lap of a negative-cost directed cycle through . Repetition makes both unrestricted distances . Clamping at zero and omitting its update would instead leave the stationary labels , concealing that behaviour. Initialization specifies the cost of the empty directed walk; it does not forbid cheaper nonempty returns to the root. Cycle detection must test every relevant directed edge, including those whose relaxation updates the root.
Bit complexity 2026-10-31
The number of elementary operations on bits required by an algorithm. Arithmetic-operation counts treat operations on entire integers as units, whereas bit complexity charges for the sizes of their operands. An algorithm using few multiplications can therefore require substantially more bit operations when the operands grow. State the model when comparing bounds for repeated squaring or dynamic programming counts.
Box nesting Created 2026-10-24 Updated 2026-10-31
Represent a -dimensional box by its side-length vector and allow axis permutations. A box fits another when its permuted dimensions are all strictly smaller. Sorting each vector reduces containment to coordinatewise strict comparison, by the sorted-coordinate criterion for box containment. For an input-order-preserving subsequence, the longest chain ending at position has one plus the greatest chain length at an earlier fitting position. This last-box decomposition proves the dynamic programming recurrence. Sorting all dimensions and testing all ordered index pairs takes running time. Arbitrary reordering is a different convention, handled by the containment Directed acyclic graph.
Critical path method 2026-10-14
The critical path method calculates an earliest schedule, a latest schedule for a chosen finish time, and each activity's task float. A critical path is a start-to-finish graph path whose total duration is greatest. There can be several such graph paths, and every one constrains completion. In the six-activity project scheduling example, the critical graph path is A-C-D-F, of duration .
Add a zero-duration source before every initial activity and a zero-duration sink after every terminal activity. Give each edge weight , including zero weight on edges leaving . This produces a weighted graph in which a graph path's weight counts every activity on it exactly once. The possible source-to-sink graph paths in our example, omitting the dummy endpoints, are A-B-D-F with weight 8, A-C-D-F with weight 10, and E-F with weight 4.
Every feasible schedule must accommodate each of these sequential chains. Consequently,
This bound applies to all source-to-sink graph paths, not just the one we happen to inspect. The critical path method attains the bound by setting each activity's earliest start to the maximum of its predecessors' earliest finish times:
Evaluate this recurrence in a topological order, obtained by topological sorting. Each satisfies every incoming optimization constraint, so these times form a feasible solution. The same recurrence calculates the greatest weight of a graph path from to ; hence the feasible finish matches the lower bound. This is dynamic programming on a Directed acyclic graph, rather than an enumeration of all graph paths. See Paul Johnson, Scheduling and longest paths, longest-path algorithm. The linear programming formulation and its certificate are developed in project scheduling duality and unit-flow certificate for project duration.
For our project scheduling example, , , and the two merges give
F finishes at 10. All six activities are completed, even though E is absent from the critical graph path. Recording which predecessor attains each maximum lets us trace a critical graph path backward from the sink; retaining tied choices exposes multiple critical graph paths.
Now fix the project start at zero and the finish at . The latest starts come from a backward pass in reverse topological order:
Every activity must finish by the earliest of its successors' latest starts, explaining the minimum here. This gives , , , , , and . These latest times themselves form a feasible solution finishing at 10. The backward calculation depends on the chosen finish time; a later deadline would give different latest times and task floats. The forward and backward passes are described in Olivier de Weck, MIT ESD.36 Lecture 2, slides 22–29.
ActivityEarliest start Earliest finish Latest start Latest finish Task float
A03030
B35572
C37370
D79790
E03696
F9109100
Figure 1.
Earliest solid and latest hollow activity bars for the critical path method, with task floats of 2 for B and 6 for E
. Details.
Changing a duration can change which graph paths are critical. If B's duration becomes 4, A-B-D-F and A-C-D-F both take 10: there are two critical graph paths. Shortening C alone then cannot reduce the finish time, because the chain through B still takes 10. If B's duration instead becomes 5, the earliest starts of D and F become 8 and 10, and the finish becomes 11. A-B-D-F is now the unique critical graph path; C has task float 1 relative to that new optimal finish. These calculations show why the critical path method is useful for understanding where a duration change matters, even in a project containing many parallel activities.
Dynamic program 2026-10-20
An algorithm that uses dynamic programming: it computes and stores solutions to overlapping subproblems, then combines them through a recurrence relation.
Dynamic programming Created 2026-09-24 Updated 2026-10-20
Dynamic programming solves a mathematical optimization problem by choosing reusable subproblems, recording their value functions, and combining already solved cases through a recurrence relation. Its attraction is that many possible decision histories can share one continuation calculation. A dynamic programming state must retain everything needed to determine the allowed future choices and their rewards. The 0-1 knapsack problem, for example, needs both the available capacity and which items remain available; capacity alone would lose the restriction that each item can be used at most once.
Two ideas explain when this works. Optimal substructure makes an optimal continuation valid inside a larger optimal solution. When subproblems overlap, storing each answer avoids repeated work: memoization computes entries as needed, while a table fills them in dependency order. Start from known base cases. For a problem indexed by increasing size, compute smaller cases first; for a finite sequence of future decisions, work backwards from the terminal reward, as in the Bellman equation. See Bertsekas, MIT lecture 2: optimality and state augmentation.
Consider a 0-1 knapsack problem with item weights , item values , and capacity . Define the value function to be the largest total item value obtainable from the first items with total weight at most . Here and specify the dynamic programming state. All weights and capacities are nonnegative integers. The empty selection supplies the base case . The recurrence relation is
The two candidates skip or take item . Both use the previous row, so taking item cannot take that same item again. The condition prevents a negative remaining capacity; no entry with is needed. The optimal substructure is concrete: after taking item , its companions must solve the smaller 0-1 knapsack problem on the first items with capacity . Otherwise replacing them by a better feasible selection would improve the whole selection. Compare [ref]; those notes index the remaining items in the opposite direction.
The full computation is small enough to see at once:
For example, and . Choosing the feasible item with largest individual value takes weight , earns , and leaves capacity , which cannot fit another item. This greedy algorithm misses the two-item selection of weights and , whose value is . This example tests the largest-individual-value rule; choosing by value divided by weight happens to find the optimum here.
Figure 1.
A knapsack table builds the optimal value from smaller subproblems
. The value function of this 0-1 knapsack problem is computed row by row. Outlined entries show the reconstruction of an optimal selection: skip weight 4, take weight 3, then take weight 2. The total weight is 5 and total value is 7. Details.
The number is the optimal value, while the choices attaining it form a control policy. To reconstruct one optimal selection, start at . Equality with allows skipping item . At , taking item gives , so continue to . Take item and finish at . In a tie, either maximizing choice suffices to recover one optimum. Recording choices during the calculation or comparing stored entries afterwards recovers the control policy; a final optimal value alone does not describe the selection.
Figure 2.
Knapsack dependencies and one optimal reconstruction
. Each node is a dynamic programming state labeled by its value function. Arrows point to the earlier-row entries used in the recurrence relation, forming a Directed acyclic graph. Dashed arrows skip an item; blue arrows take it. The orange graph path reconstructs the optimal selection with value 7. Compute in the opposite direction to the arrows, beginning at the zero base row. Details.
For items and integer capacity , the table uses time complexity and space complexity , counting arithmetic operations and stored numbers using Big O notation. This is pseudo-polynomial time: when weights and capacity use the binary numeral system, the capacity needs only digits. A capacity near creates about columns despite needing only about digits. Thus this algorithm is practical for moderate capacities but does not establish polynomial time in the encoded input length. See MIT 6.006 recitation 19: knapsack and input size. For the optimal value alone, one array reduces space complexity to : for each item, update capacities in descending order, from down to . Ascending order would read entries already updated for that item and could reuse it. Reconstruction then requires extra information or recomputation.
The link between the knapsack problem and dynamic programming is already explicit in a 1957 paper by Richard Bellman at RAND: its abstract discusses an exact knapsack problem solution using functional equations and cites his 1957 book. See Bellman, Comment on Dantzig's Paper on Discrete Variable Extremum Problems (1957).
Align two complete strings using matching letters or a letter opposite a gap, with no unequal-letter columns and no double-gap columns. Give each match score one and each gap penalty . The dynamic programming table for prefixes starts with and . Its last-column cases give the displayed recurrence, where the diagonal candidate is omitted on a mismatch. Construction takes time for positive lengths and space with full alignment traceback.
An alignment with matches has gaps and score . Therefore a longest common subsequence determines its optimum. A finite mismatch penalty would solve a different problem.
Group testing 2026-10-20
A testing strategy that pools samples to determine which individuals satisfy a binary condition. A negative pool rules out every member, whereas a positive pool requires more information to identify the affected individuals. Conditional probabilities and dynamic programming can determine an efficient adaptive strategy under a specified model.
Let be the minimum weight of a route from a fixed source to using at most edges; repeated vertices are permitted. Initialise to zero at the source and infinity elsewhere. Every feasible route either already uses at most edges or appends one edge to such a route, proving the displayed dynamic programming recurrence. Reading exclusively from the previous row enforces the edge budget. Negative cycles cause no unbounded objective because the budget is finite. Each round scans all edges, costing when only edge-incident vertices and the specified endpoints are processed. With nonnegative weights, cycle removal gives an equally good or better simple path within the budget.
Linear-time multiplication in an automatic structure Created 2026-10-06 Updated 2026-10-14
Fix the first tape of a group multiplier automaton and use dynamic programming over automaton states and output-padding status, retaining predecessor pointers. The pumping of a group multiplier automaton bounds the search by layers, each of fixed size. This constructs a representative of in time without assuming uniqueness of representatives.
Longest increasing subsequence Created 2026-09-28 Updated 2026-10-14
A longest increasing subsequence is an increasing subsequence of maximum length. Write that length as , with for the empty sequence; a nonempty input has . Several selections can attain the same maximum. Here uses the weak convention ; write for the maximum length of a strictly increasing subsequence. For , these lengths are three and one respectively; for an input with distinct values they agree.
For , the answer is , attained at indices , while . One useful interpretation is the smallest number of deletions needed to make the surviving sequence nondecreasing:
Indeed, keeping a longest increasing subsequence attains this bound, and any valid remaining sequence is an increasing subsequence, so cannot have more than terms. In this example the answer is . This makes a measure of how much order can be recovered without moving any observation.
A table that ends at each position. Let be the maximum length of an increasing subsequence ending specifically at position . The dynamic programming recurrence relation is
The zero covers a selection consisting only of . Otherwise its penultimate index is an eligible ; append to an optimal selection ending there. Fill entries in increasing index order. For strictly increasing subsequences, change the comparison to . The strict version and reconstruction are developed in University of Toronto, CSC373 tutorial 4 solutions (2018), exercise 2; the weak version follows by allowing equality at the append step.
In the worked input, the weak table is and the strict table is . At the second , equality extends the first in the weak table. The final entry is only one, although the optimum is four: the best increasing subsequence need not finish at the last input position. Record a maximizing predecessor whenever . Following these stored indices from any position maximizing , then reversing them, gives an actual longest increasing subsequence. For the weak example the backward chain is .
Figure 1.
Skipping positions and allowing equal values changes the optimum
. An original toy input, not measured data. The colored selection keeps indices and values . The two dynamic programming rows give the best lengths ending at every position; the backward arrows reconstruct the weak longest increasing subsequence. Details.
Scanning all earlier positions for each uses time complexity and space complexity for lengths and predecessors, using Big O notation and assuming constant-time comparisons and operations on indices.
Keep the easiest ending to extend. The faster algorithm maintains a minimum-tail table for increasing subsequences: is the smallest final value of any length- increasing subsequence in the processed prefix. For equal lengths, a smaller ending permits every future extension allowed by a larger ending. Thus only one best ending per length is needed. The table is nondecreasing, since removing the last term of a length- selection gives . Start with an empty table. On reading , use binary search to find the first entry strictly greater than : replace it by , or append if there is no such entry. Its position is one beyond the longest existing length whose ending is at most . See Liben-Nowell, Vee and Zhu, section 3.1 and Figure 1.
Duplicates determine the binary search rule: weak increase replaces the first , whereas strict increase replaces the first . In Python these positions are returned by bisect_right(T, v) and bisect_left(T, v) respectively, counting positions from zero. Replace an entry or append; do not insert and shift the remaining entries. The documented equality rules are in Python documentation, bisect_left and bisect_right. Each search takes comparisons, giving time complexity , conventionally for , and space complexity for the weak length alone.
Figure 2.
Two binary-search tie rules give different minimum-tail tables
. Original exact traces for the same toy input, not measured data. Each cell shows a tail value and the input index supplying it; the outlined cell was updated in that row. At the second , the weak algorithm appends and the strict algorithm replaces. The final weak table has length four, but its supplier indices are not in increasing order. Details.
A length certificate needs separate reconstruction. The final weak tail values are , but they do not form an increasing subsequence of this input: the zero occurs last. Each table entry certifies a selection of its own length; the entries need not come from one compatible selection. To recover a longest increasing subsequence during the fast algorithm, store a supplier index for each tail and a predecessor index for each input position. Before replacing slot , save , or no predecessor if , then set . Later replacements leave saved unchanged. Follow predecessors from the final and reverse. This uses space complexity and returns indices for the weak trace. The same construction works with the strict comparator; compare the two auxiliary arrays in CP Algorithms contributors, restoring the subsequence after binary search.
Deleting or changing one term. If deletes position , then
Deleting cannot create a longer increasing subsequence; removing position from a previously optimal selection loses at most one term. If instead changes just the value at position , both inputs have the same deleted sequence, so their lengths each lie between its length and its length plus one. Consequently . These bounds also hold for strictly increasing subsequences. In the weak example, deleting either lowers the length to three, while deleting the final zero leaves it four. This is a Lipschitz bound for single-term edits, regardless of the numerical size of a replacement. Insertion has the same bound by reversing deletion, so insertions, deletions or replacements can change by at most .
For historical context, [ref] studies the comparison count for distinct elements of a totally ordered set. Its distinctness assumption makes the weak and strict conventions coincide. No distinctness assumption is needed for the comparator-specific algorithms above.
Longest path Created 2026-10-25 Updated 2026-10-31
A longest path maximizes path length, either the number of edges or the sum of specified edge weights, under the stated endpoints and simple-path convention. In a general graph, imposing vertex simplicity makes the optimization computationally difficult; a Directed acyclic graph admits a direct dynamic programming solution. Allowing arbitrary walks instead requires care with reachable positive cycles. The convention permitting a zero-edge path gives a possible value zero even when all nonempty paths have negative weight.
Let have matrix dimensions , where are positive integers. For , define as the minimum scalar multiplication cost of the contiguous matrix product . The endpoints of an integer interval identify a dynamic programming state. A single matrix needs no matrix multiplication, giving the base case . At the final matrix multiplication, split after :
The two subproducts have matrix dimensions and , regardless of their internal grouping. The recurrence relation adds their optimal costs and the final scalar multiplication cost.[ref]
Why is this optimal substructure? For a chosen final split , replacing either subproduct's grouping by a cheaper one leaves its matrix dimensions and exact matrix product unchanged, so it decreases the whole cost by the same amount. Therefore an optimal grouping can use optimal groupings on both sides. Conversely, each candidate in the recurrence relation joins two achievable groupings. Mathematical induction on , starting with the single-matrix base case, proves that the minimum is achievable and no grouping is cheaper.
There are also overlapping subproblems: while evaluating the different final splits of , the cases and both request the cost of . Recursion without reuse recomputes this answer; memoization or a dynamic programming table stores it once. Fill the table by increasing length , so both dependencies are ready. Record an attaining split alongside each cost.[ref]
The dynamic programming table has cost entries. For length , there are entries and possible splits, so the exact number of candidate evaluations is
Under the unit-cost assumption that arithmetic operations, comparisons and access to stored costs each take constant time, this gives time complexity and space complexity , using Big O notation. These bounds concern choosing a grouping from the matrix dimensions; they exclude the subsequent matrix multiplication work. If the dimensions or costs require arbitrarily long integers, their arithmetic and storage costs must also be counted.
Extend the original example by a matrix with matrix dimensions , so . The Catalan number counts all possible groupings. Their scalar multiplication costs are
The optimum is , with cost . Enumeration makes a useful check here, but dynamic programming reaches the same answer by solving ten integer intervals, including the four single-matrix base cases:
For example, . The three final-split candidates for the full matrix product supply a compact certificate:
The first candidate already uses the better grouping of ; the worse need not be reconsidered at the top level. This is how optimal substructure lets the table represent all five possibilities with only three final candidates.
Figure 1.
A four-matrix cost table and the splits certifying the optimum
. Original dynamic programming calculation for . Orange entries are the nonsingleton integer intervals used in the recovered optimum. The binary tree follows stored splits down both children to the single-matrix base cases; the final candidates certify the cost . Details.
Read , which separates from . Then separates from , and separates from . This recursion stops at every , returning the corresponding matrix name. Combining the returned expressions recovers , rather than only its cost. Every recursive call uses a shorter integer interval, establishing algorithm termination; a tied minimum may choose any attaining split. The recovered binary tree has leaves and internal nodes, so reconstruction takes steps. Its attraction is the separation between an enormous family of groupings and a small set of reusable dynamic programming states.
Root a finite tree. The two dynamic programming states are the optimal size in the descendant subtree when its root is included, , or excluded, . The sums run over its children. Inclusion forces every child to be excluded; exclusion permits each child's better state. Child subtrees have no edges between them, which proves independence of these choices. The leaf states are , and the root's better state gives the optimum.
A postorder traversal computes the states in time and storage. Reconstruct a set by following an attaining root choice and the same child constraints, breaking ties arbitrarily. The empty and singleton cases use the ordinary non-strict subset convention.
Attach nonnegative edge scores to edge-labelled walk matching. For each layer and endpoint, keep the greatest product over matching prefixes. Only edges with the required current label enter the maximum. Multiplication by a nonnegative score preserves order, proving the dynamic programming recurrence. Store a predecessor for each reachable layer entry to recover a maximizing walk. A reachable score of zero must be distinguished from no matching walk: keep reachability separately or use an impossible negative sentinel and skip it before multiplication. The score is the defined product; interpreting it as a physical event probability can require extra independence assumptions.
Under constant-cost lookup and integer addition, Memoized Fibonacci evaluation has time complexity in Big O notation, retaining values. A hash table needs its own lookup-cost assumptions; an array indexed by avoids hash collisions in this example. Memoization removes repeated bodies, but also pays for keys, lookups and retained answers. A workload without reuse can pay those costs without saving evaluations.
The call stack remains. Left-first recursion descends through arguments before returning, giving simultaneously active frames for . Therefore the auxiliary space complexity includes frames as well as table entries in the constant-size-value model. An iterative bottom-up dynamic programming calculation removes these recursive frames; retaining only the two previous Fibonacci numbers suffices when only the final value is wanted, but discards the table useful for later requests.
Exact Fibonacci numbers do not remain constant-size values. For , the recurrence relation gives , so the representation of as a binary number has order bits. With ordinary addition costing order bit operations on such operands, the additions cost order bit operations in total. Retaining all values also requires order bits of value storage, before keys and frame overhead. The linear bound counts additions under its stated cost model; it is not a linear bound on exact integer arithmetic in bits.[ref]