An algorithm is a finite, precise procedure for transforming an input into an output.
Here "finite" refers to the description: a short algorithm can perform arbitrarily many steps on increasingly large inputs. Solving a computational problem additionally requires termination and the specified output on every permitted input. State assumptions explicitly: binary search requires a sorted array.
An algorithm is an idea that can have implementations in different programming languages. Its explanation should make three things visible: the permitted inputs, the rule for each step, and the meaning of the returned output. Algorithm correctness then separates finding the right answer from eventually finishing; time complexity asks how much work finishing requires.
A particularly useful design question is: what knowledge survives each step? In binary search, it is the location of every possible match inside the remaining candidate range. Writing that fact as a loop invariant turns an intuitive shortcut into a procedure whose discarded candidates can be justified. This often helps discover the algorithm, rather than merely check it afterward.
Algorithm selection chooses an algorithm for a particular problem instance using information available before or during its solution. The available candidates form an algorithm portfolio. John R. Rice's 1976 treatment formalized the relationship between problem descriptions, descriptive features, algorithms and performance criteria.[ref]
An original runtime example shows the potential benefit. Suppose algorithms and take and seconds on two equally likely instance types. Always choosing gives mean seconds; always choosing gives seconds. A selector that reliably recognizes both types and chooses the faster algorithm gives mean seconds before selection overhead. If computing its features and choosing costs another second, the total becomes seconds. The gain comes from complementary performance, not from either candidate being universally faster.
The hypothetical -second result assumes perfect decisions. A real selector can misclassify instances, spend time extracting features or encounter inputs unlike its training examples. Its complete measured runtime includes those costs. Looking up the faster solver after both have finished supplies a useful comparison bound, but does not itself implement an online choice.
Algorithm configuration instead searches settings of a parameterized target algorithm. The two ideas can be combined by selecting among configured candidates, provided the evaluation states what was tuned, what was selected and which instances were reserved for testing.
An algorithm portfolio combines several candidate algorithms or algorithm runs to exploit differences in their performance. It includes a policy for choosing or allocating work, rather than merely naming a collection. A parallel algorithm portfolio runs candidates concurrently; a sequential algorithm portfolio allocates time on one processor. The original 2001 study compared these approaches and restart strategies on specified distributions of search problems.[ref]
Consider invented runtimes seconds and seconds on two equally likely instance types. Either algorithm alone has mean seconds. Perfect per-instance algorithm selection would take one second before selection overhead. Running both on independent full-speed processors and stopping at the first answer also takes one second under this model, but uses two processors.
For a different policy, run for at most five seconds, then start if needed. The two completion times become and seconds, giving mean seconds. This invented sequential algorithm portfolio saves time relative to either fixed choice, without matching the two-processor wall time.
Complementary runtimes make these examples work. If all candidates are slow on the same instances, diversity in names supplies no such benefit. Compare wall time, total computing work and overhead separately, and test the allocation policy on new instances. The best completed run chosen retrospectively is a comparison bound, not automatically an implementable selector.
An algorithm portfolio schedule specifies how computational resources are assigned to members of an algorithm portfolio over time. For a sequential algorithm portfolio, it states which algorithm receives each time interval, whether interrupted work is resumed or discarded, and when computation stops. A parallel algorithm portfolio also needs a processor allocation and a rule for accepting and combining results. Listing candidate algorithms alone does not specify a schedule.
An original interleaving example makes the distinction between processor time and elapsed time explicit. Suppose algorithms A and B need respectively and seconds of processor time on a particular input. Give A one second, then B one second, repeating while preserving both states and stopping at the first accepted result. A receives its third second during elapsed interval , so the portfolio finishes at seconds. At that point A has used processor-seconds and B has used . With two dedicated processors, the corresponding parallel algorithm portfolio would finish at seconds. These calculations assume no algorithm portfolio switching overhead and no resource contention.
More generally, let be processor time supplied to candidate by elapsed time , and let be its required processor time. In the resumable, interference-free model, the completion time is
Discarding a state on every interruption changes this model: separate short runs do not necessarily accumulate into one longer run. The original portfolio study compared parallel, interleaved and restart execution precisely because these are different policies.[ref]
Choose an objective before comparing algorithm portfolio schedules: expected value of running time, probability of finishing by a deadline, and total computing work need not favor the same allocation. A schedule chosen using retrospective runtimes also requires evaluation on inputs that did not determine the schedule.
A sequential algorithm portfolio allocates one processor's time among candidate algorithms or runs. Its algorithm portfolio schedule determines which candidate runs, when to switch and whether an interrupted run is resumed or abandoned. The original portfolio study compared single-processor interleaving and restart policies with parallel execution.[ref]
Consider original runtimes seconds and seconds on two equally likely input types. Either fixed choice has mean or seconds. Run for at most four seconds, then start if has not finished. The two completion times are and seconds, so the scheduled mean is seconds. The schedule succeeds because the candidates have complementary performance.
Algorithm portfolio switching overhead can erase that gain. If the switch costs seconds whenever it occurs, the second completion time becomes seconds and the mean becomes seconds, worse than always running . The cost must be charged to the actual switching events, rather than added equally to every instance.
A timeout also does not say that the interrupted candidate would never solve the input. Resuming preserves previous search work only if the implementation supports it; restarting begins a different run. Record budgets, state retention, random seeds and the final stopping rule when reporting a sequential portfolio's performance. A good schedule on measured inputs still needs evaluation on unused inputs.
Algorithm portfolio switching overhead is elapsed time or computing work spent changing the active member of an algorithm portfolio, beyond the useful work counted for the candidate algorithms. It can include a context switch, saving or restoring search state, rebuilding data structures and warming a processor's working data. The measured cost depends on the implementation and on what its runtime accounting already includes.
For an explicit model, give one candidate seconds of useful work, then spend seconds switching. Repeating equal intervals indefinitely gives useful-time fraction
For and , this is . Reducing the useful interval to with the same switch cost drops the fraction to . Small time slices improve responsiveness but can consume more of the budget in switching.
Terminal bookkeeping matters. In the illustrative algorithm portfolio schedule where A and B alternate one-second useful intervals, A completes after its third interval and B has received two. Four switches occur before completion. With per switch, elapsed time is ; there is no fifth switch after the stopping rule has fired. Comparing this with the zero-overhead trace isolates the stipulated switching cost.
The original portfolio experiments distinguish interleaving from parallel and restart execution.[ref] Applying such policies requires distinguishing switching cost from algorithmic work that is abandoned. If a run is discarded and restarted, lost progress changes the completion process itself; treating it as a fixed additive switch cost can misrepresent the sequential algorithm portfolio. Report whether timings include initialization, state transfer and result checking, and measure the actual switching events.
A parallel algorithm portfolio runs multiple candidate algorithms or randomized runs concurrently and combines their outcomes under a stopping policy. For a first-solution problem, an ideal policy stops all candidates when one returns an acceptable solution. The original portfolio study investigated how differing runtime distributions can make such combinations effective.[ref]
If candidates have dedicated processors, negligible coordination overhead and completion times , the first completion is . For independent completion times,
The equation follows because every candidate must still be running for the minimum to exceed . Independence is an assumption about the runs, not a consequence of using different processor cores.
For an original two-point model, one randomized run finishes in one second with probability , otherwise in seconds. Its mean is seconds. Two independent runs are both slow with probability , so first-completion time has mean seconds. If their runtimes are perfectly correlated, the mean remains seconds. Repeating identical hard behavior offers no independent escape route.
Wall time and computing work differ: running two full-speed processors until the first completion uses twice that wall time in processor-seconds in this model. Shared memory, bandwidth contention and communication can further change actual timings. Report those resources and the answer-acceptance rule before interpreting a parallel speedup.
Algorithm configuration chooses settings of a parameterized algorithm to improve its performance on a specified class of inputs. An algorithm parameter space describes the allowed settings; the objective function may measure runtime, solution quality or another declared cost. The target algorithm solves the instances, while a configuration procedure searches for settings under which it works well.[ref]
For an original example, suppose two settings have runtimes seconds and seconds on two instance types. With equally likely types, the mean costs are and seconds, favouring . If the first type instead has probability , the means become and seconds, favouring . There is no distribution-independent best setting in this example: the intended workload is part of the optimization problem.
Measured cost estimates also depend on time limits, random seeds and which instances were sampled. Report those choices and evaluate the chosen setting on previously unused instances. Reusing the tuning results as the only evidence of improvement rewards settings that happened to fit the observed sample.
ParamILS supplies a concrete search procedure for this problem. Algorithm selection is a related decision about which algorithm to run for an instance, whereas the example above fixes one parameterized target and chooses its settings. In both cases, specifying what may change is necessary to interpret an experimental comparison.
An algorithm parameter space, commonly written , is the set of allowed settings for a parameterized algorithm. It is the search space of algorithm configuration, rather than the set of problem instances that the target algorithm must solve. ParamILS explicitly accounts for parameters whose relevance depends on other settings.[ref]
For an original finite example, let a mode be either or . Mode has an extra setting , while mode ignores . A rectangular encoding has tuples, but only four distinct effective configurations:
The star means that the conditional algorithm parameter is inactive. Treating the three encodings of as three distinct experiments spends effort revisiting the same behavior. If is a forbidden parameter combination, the valid effective space has three members.
The representation also determines what a nearby configuration means. A search that changes one active parameter can move among the settings or change mode; changing an inactive value alone does not change behavior. Thus the number of encoded tuples, number of meaningful settings and neighborhood used by local search are separate design choices.
Continuous settings require declared ranges and a search method that supports them; replacing a range with a finite grid changes the problem being searched. Whatever the representation, a returned setting must be valid in before its measured cost can be compared with other candidates.
A forbidden parameter combination is an assignment excluded from an algorithm parameter space by an explicit validity rule. Each individual value may be allowed, while their joint use is not. The ConfigSpace guide implements this distinction using forbidden clauses and their conjunctions.[ref]
For an original counting example, let mode , cache and worker count . There are initially eight assignments. Suppose the rules forbid both and . Each rule excludes two assignments, but they overlap on one:
Subtracting four without accounting for the overlap would reject an assignment twice. The count can also be checked directly: all four cache-off assignments are valid, and only survives with the cache on.
This differs from a conditional algorithm parameter. A condition says whether a setting is active; a forbidden rule says that an otherwise represented combination is inadmissible. An inactive setting can be irrelevant without making the parent configuration invalid.
Validity is also distinct from the objective function. A slow valid run has a measured performance cost; a forbidden combination lies outside the declared search domain. Giving every invalid combination an arbitrary large cost changes the mathematical model and can waste evaluations or accidentally make an invalid result appear competitive. Check the validity rule before treating a proposed configuration as an experiment.
A conditional algorithm parameter matters only when a stated condition on other settings holds. In an algorithm parameter space, the condition determines whether the child parameter is active. The ConfigSpace guide samples conditional settings only when their activation conditions are met.[ref]
For an original example, an algorithm has modes plain and tuned. A depth setting affects only tuned mode. The naive rectangular encoding has eight pairs, but the distinct effective settings are
The four plain-mode encodings describe the same effective choice, so there are five settings, not eight. The star denotes inactivity; it is not an additional depth value used by the algorithm.
ParamILS excludes local moves that change only an inactive parameter, since such a move does not alter effective behavior.[ref] Switching from plain to tuned activates a choice of depth, while changing an unused plain-mode depth alone supplies no new measured behavior.
A forbidden parameter combination instead rules out a joint assignment. Inactive does not mean forbidden, missing data or a numeric zero. Recording the mode and activity conditions makes a returned configuration interpretable, especially when comparing costs or reusing settings in another implementation.
ParamILS is a framework for algorithm configuration based on iterated local search. It explores an algorithm parameter space using improvements to nearby configurations, perturbations and occasional restarts. BasicILS compares configurations on a fixed number of matched training runs; FocusedILS adapts how many runs support a comparison.[ref]
The distinctive efficiency idea of adaptive capping is to stop spending evaluation time on a candidate once it cannot win the comparison under the stated cost model. Consider an original example with three fixed instances and mean nonnegative runtime as the objective function. A fully evaluated incumbent has total time seconds, hence mean seconds. If the first two candidate runs already total seconds, even a zero-time final run leaves mean at least . Rejecting that candidate does not require finishing the last run.
This argument depends on its assumptions: the comparison uses the same fixed instance set and a lower bound on unfinished cost. It cannot be transferred unchanged to arbitrary quality scores or a different timeout penalty. The paper distinguishes trajectory-preserving capping from a more aggressive heuristic variant; faster rejection does not always carry the same guarantee.[ref]
The method turns tuning into a measured optimization experiment, but a good observed configuration is not a proof of a global minimum. The neighborhood, evaluation budget and deployment workload remain relevant to what the returned setting establishes.
FocusedILS is the ParamILS variant that adapts the number of evaluation runs assigned to different configurations. Its pairwise comparisons use common benchmark instances and random seeds, extending the evidence when necessary instead of comparing arbitrary means from different run lists.[ref]
An original example shows why unequal evidence needs care. Suppose configuration has completed two runs with costs seconds, while has four costs seconds. Their available means, and , mix different instance coverage. On the two shared runs the comparison is against . If extending to the same four runs gives , its mean becomes , reversing the ranking against 's . Matching the evidence does not prevent a ranking from changing when more evidence arrives.
The run allocation and the configuration search are different layers. Iterated local search proposes which settings to compare; the FocusedILS comparison procedure determines how much measured evidence supports the decision. BasicILS instead uses a fixed evaluation count . Both still depend on a declared cost statistic and a representative workload.
The example is a finite-data illustration, not a confidence interval or proof about unseen inputs. A setting selected after adaptive evaluation should be assessed on unused instances, with the full tuning budget recorded. The cost of finding the configuration and the subsequent cost of running it answer different questions.
BasicILS is the fixed-evaluation variant of ParamILS. In , competing parameter settings are compared using the same benchmark runs, with matched instances and random seeds.[ref] The comparison rule supplies the cost estimates used by the surrounding iterated local search.
For mean runtime, write
where is the recorded cost on the specified run. Consider invented costs seconds and seconds. With only the first run, appears better, . Across all three runs, its mean is seconds while remains at seconds. Choosing therefore affects both evaluation expense and how much instance variation the estimate captures.
Using the same run list makes that example a comparison on common evidence. Comparing only on easy instances with on harder ones would answer a different question. Even a matched finite sample can be unrepresentative of future workloads, so the final configuration still needs evaluation on unused instances.
FocusedILS changes the allocation of runs rather than requiring the same fixed for every explored candidate. Adaptive capping can avoid completing an already-lost runtime comparison under a valid lower-bound rule. Neither modification makes a finite observed mean a proof of the best possible setting in the entire algorithm parameter space.
Adaptive capping reduces the cost of algorithm configuration by ending an evaluation when a valid bound already rules out winning the comparison. For nonnegative runtimes, completed runs and elapsed time in the current run can provide a lower bound on the final cost. ParamILS distinguishes trajectory-preserving capping from a more aggressive heuristic policy.[ref]
Consider an original comparison of mean runtime over fixed runs. The incumbent has mean seconds, or total seconds. A candidate has completed runs taking and seconds, and its third run has already taken seconds. Even if all remaining work took zero time, the final mean would satisfy
Continuing that candidate cannot improve this comparison. The partial total itself supplies the certificate; no prediction of the remaining runtime is needed.
By contrast, after only the first two runs, their observed mean is , but rejecting solely on that partial mean would be invalid: the four-run lower bound is only . Two sufficiently fast remaining runs could still win. The denominator must correspond to the comparison objective.
A censored algorithm runtime is therefore not an observed completed runtime. Record the cutoff and what bound it establishes. Timeout penalties, changing instance sets or non-runtime objectives require a bound compatible with their own scoring rules. A heuristic early-stopping rule may be useful without preserving the same search decisions as full evaluation.
A censored algorithm runtime is an evaluation that ends without observing the algorithm's actual completion time. A timeout or adaptive capping limit can establish that the run had not finished by the cutoff, supplying right censoring rather than an exact completed runtime. The ParamILS capping analysis uses such elapsed-time information to bound comparisons without finishing every run.[ref]
Write for completion time and for a stopping limit. A simple record is
where means completion was observed. The event flag is essential: the same stored duration can mean a completed run or only a lower bound on a still-running computation.
For an original example, two completed runs take and seconds and a third is stopped unfinished at seconds. Averaging the stored durations gives seconds, but that is only a lower bound on the mean of the actual completion times. If the third would take seconds, the true mean is seconds. Discarding it entirely gives seconds and removes the difficult run from the comparison.
Keep exact observations, cutoff information and any timeout penalty separate. A penalized benchmark score may deliberately assign a stated cost to a timeout; that score is not an observation of . Estimating completion-time distributions additionally requires assumptions about how stopping limits were chosen, particularly when the limits depend on earlier performance.
A state-space search solves a problem by exploring a transition system: a state records the current situation, a transition relation specifies legal moves, and a goal state specifies success. The answer is usually a path in a transition system, rather than just the final configuration. This separates modeling the problem from choosing the search algorithm.
For a sliding-tile puzzle, the state is the arrangement of tiles and the empty square; one move slides a neighboring tile into that square. Breadth-first search finds a solution using the fewest moves when all moves have equal cost. Depth-first search can use less working storage but need not find a shortest solution. Remembering visited configurations prevents repeatedly exploring a cycle. The same formulation applies to route finding and automated planning.[ref]
A graph algorithm computes a property of a graph or constructs a related object from its graph vertices and graph edges. The input representation matters: an adjacency list lets an algorithm inspect the neighbours of one graph vertex without scanning every possible pair of graph vertices, whereas an adjacency matrix provides direct tests for individual graph edges.
For example, breadth-first search finds every graph vertex reachable from a starting graph vertex . Mark , place it in a FIFO queue, then repeatedly remove the oldest marked graph vertex and mark/enqueue each previously unmarked neighbour. A graph vertex is enqueued at most once, so scanning adjacency lists costs . The FIFO queue processes distance layers in order; the first discovery of a graph vertex supplies a shortest graph path in an unweighted graph.
For graph edges , , , starting at discovers before , with distances . The same graph can support different questions: depth-first search investigates traversal structure, Dijkstra's algorithm uses nonnegative edge weights for shortest graph paths, and a minimum spanning tree minimizes the total weight needed to connect an undirected graph. Matching the algorithm to its assumptions is part of modelling the problem.
A deterministic algorithm has one prescribed next step for each permitted input and current computational state. Thus the same input and initial state give the same execution trace and, if execution terminates, the same output. This is a statement about the abstract transition rules, not about identical elapsed time on different computers.
Binary search with a fixed midpoint rule is deterministic: every comparison determines which remaining interval is searched next. Quicksort with a fixed pivot-selection rule is also deterministic, even though different inputs can produce very different running times. Determinism therefore does not imply a constant or small time complexity.
A randomized algorithm additionally receives random choices. Fixing its entire random-choice sequence makes its subsequent execution deterministic, but averaging over those choices is essential to its randomized guarantees. A Nondeterministic Turing machine is a different mathematical model: its branches describe possible computation paths, rather than a probability distribution supplied by an implementation.
In the geometry of numbers, a lattice algorithm works with a Euclidean lattice, usually specified by linearly independent vectors whose integer linear combinations form
The basis of a Euclidean lattice is not unique. For example, and generate the same Euclidean lattice as and : replace the second vector by itself minus 100 times the first. This integer linear combination is reversible, so it changes the representation without changing the set of Euclidean lattice points.
Lattice reduction seeks a more useful basis of a Euclidean lattice, with shorter and less nearly dependent vectors. The Lenstra-Lenstra-Lovász lattice basis reduction algorithm combines integer basis changes with Gram-Schmidt orthogonalization and comparisons controlling the quality of the result. It is a polynomial-time example, but it does not generally return an exactly shortest vector.[ref] Better bases make geometric searches and lattice-based cryptography analysis more practical. The geometry and the sizes of the integer coordinates both matter: a small number of arithmetic steps need not imply a small bit complexity.
A concurrent algorithm coordinates activities whose execution steps can overlap in time or be interleaved. Correctness must cover the allowed thread interleavings, including executions in which one activity pauses while another continues. Merely testing one convenient schedule does not establish the required property.
Suppose two activities increment a shared counter initially zero by separately reading, adding one and writing. Both can read zero before either writes, so the final value is one rather than two. An atomic read-modify-write can make each increment indivisible; mutual exclusion can instead protect a larger critical section. The appropriate choice depends on which shared-state invariant must survive each permitted execution step.
Leslie Lamport's Lamport's bakery algorithm illustrates the distinction between a coordination rule and assumptions about hardware. Its mutual exclusion argument orders ticket/process-number pairs, and the original proof explicitly treats reads overlapping writes rather than silently assuming every shared-memory access behaves atomically.[ref] Concurrent correctness can include safety, such as never entering two critical sections together, and progress, such as a waiting activity eventually proceeding under stated scheduling assumptions.
Lamport's bakery algorithm is a mutual exclusion concurrent algorithm in which each participating process chooses a numbered ticket before entering a critical section. Process announces that it is choosing, sets its ticket to one more than the largest observed ticket, and finishes choosing. It then waits for each other process to finish choosing and for every smaller nonzero pair to leave. Comparing identifiers breaks ties between equal tickets; setting one's ticket to zero announces departure.[ref]
For example, simultaneous choices can give processes 2 and 5 the same ticket 7; pair precedes . The choosing flag prevents treating an unfinished choice as an absent contender. Leslie Lamport's 1974 proof even permits an overlapping read to return an arbitrary value under the specified shared-register model. The mathematical model uses unbounded tickets; a bounded machine implementation must also address overflow and its memory model.[ref]
Combinatorial generation enumerates finite objects satisfying a specified structure, such as permutations, subsets or set partitions. A generation procedure must explain both completeness, meaning every required object appears, and uniqueness, meaning objects are not emitted twice under the chosen equivalence convention. Counting the objects is a different task from writing them all down.
For all length-three binary strings, a Gray code order is 000,001,011,010,110,111,101,100. Consecutive strings differ in exactly one bit. More generally, the reflected binary Gray code is for , using bitwise exclusive or. Its map is invertible: recover each binary digit of by accumulating the exclusive or of the higher Gray code digits. Thus all objects occur exactly once.
A one-bit update can be cheap while reporting a whole object is expensive. Writing every length- binary string explicitly takes at least bit writes, even if the generation state changes only once per object. Useful performance measures therefore distinguish initialization, delay between objects, working memory and the unavoidable output size.
Permutation generation enumerates arrangements of a finite collection under a stated convention. For distinct labelled objects there are permutations, so explicitly writing every length- arrangement already requires output work. Permutation generation by insertion builds each arrangement from a shorter one; the Steinhaus-Johnson-Trotter algorithm instead changes only an adjacent transposition between consecutive arrangements. Repeated values require deciding whether positions remain distinguishable. For values a,a,b, there are six permutations of labelled positions but only three distinct value strings.
Generate every permutation of a finite list by recursively permuting its tail and inserting its head into each possible position. For distinct input elements, every shorter permutation has insertion positions, giving results. Removing the distinguished head reconstructs the unique shorter permutation and insertion position.
In a Boolean matrix, find an axis-aligned rectangle containing only true entries and having maximum area. One approach first records each row's consecutive true run ending at each column. For each possible top-right corner, extend downwards, maintaining the minimum run width and maximizing height times width. This uses time complexity on an by matrix after preprocessing.
The number of consecutive true entries ending at a specified column of one row of a Boolean matrix. It is zero at a false entry and otherwise one plus the previous column's row run length, taking the value before column zero to be zero.
Studying an algorithm's resource use under a stated cost model. Time complexity, space complexity and amortized analysis answer different questions, so an operation count should specify the input-size parameter and what each primitive operation costs.
Average-case analysis measures an algorithm's expected cost when its inputs follow a specified probability distribution. If is the number of counted operations on input and is the probability of a size- input, then
The expected value is meaningful only after specifying both the input model and the counted operation. It is not an average over arbitrary anecdotes or necessarily the cost of a typical individual run.
For a successful linear search through distinct entries, suppose the sought entry is equally likely to occupy any position. Searching from the beginning uses comparisons if the entry is at position , so
For , this is five comparisons, whereas worst-case analysis gives nine. If the entry is absent with probability and otherwise has the same equal-position model, the expected count becomes . Changing the workload therefore changes the answer without changing the algorithm. Amortized analysis instead bounds the cost of a sequence of operations and need not assume an input probability distribution.
Worst-case analysis measures the largest resource use of a specified algorithm among inputs of the same size. If counts operations on input , the worst-case function is
The cost model and meaning of input size are part of the definition. A big O notation bound describes growth of this function, rather than a claim about how often the difficult input occurs.[ref]
For linear search of entries, looking for an absent item requires equality tests; finding the first item needs just one. Thus the worst-case comparison count is , even if many actual queries finish earlier. This supplies a guarantee for every allowed input, while an average-case analysis requires a stated distribution over inputs.
Arithmetic complexity counts arithmetic operations under an explicitly stated computational model. One may count additions, subtractions, multiplications and divisions over a specified field as unit operations, or distinguish their costs. This exposes algebraic structure without yet accounting for how each number is represented.
For a degree- polynomial , Horner's method sets and for . It returns using multiplications and additions. Repeatedly expanding each power independently would obscure this reuse of earlier work. An arithmetic circuit represents such dependencies as a finite network of arithmetic operations.
Bit complexity asks an additional question: how much work is required to perform those operations on the encoded numbers? Multiplying two large integers is one arithmetic operation but requires processing their bits. Intermediate numerators and denominators can also grow. Conversely, a small arithmetic-operation count does not bound round-off error; the numerical stability of an evaluation scheme is a separate property.
A method for proving that an algorithm must perform a certain amount of work: supply observations compatible with more than one possible input until enough information has been acquired to distinguish the required outputs. For exact membership in an arbitrary array, answering every inspected location with a value other than the target forces inspection of every location in the absent case, since any uninspected location could contain the target.
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.
Rearrange an array segment into a low segment containing values below a pivot and a high segment containing values at least , preserving the segment's multiset and leaving the rest of the array unchanged. The pivot need not itself occur, and either resulting segment may be empty.
An in-place scan maintains indices with and . A low value at is swapped into position and advances both indices; a high value advances only . The unexamined length is a loop variant. At exit , establishing the separation in time complexity and auxiliary space complexity. Equal values consistently belong to the high side.
Maintain consecutive regions less than a saved pivot value, equal to it, unclassified, and greater than it. Compare the first unclassified entry: move a smaller one into the lower region, advance over an equal one, or exchange a greater one with the final unclassified entry. In the last case the incoming entry still needs classification. Each step shortens the unclassified interval by one. The final equality interval is nonempty when the pivot was selected from the input; Quickselect can discard that entire interval when searching another rank. Saving the value avoids accidentally comparing against a pivot index whose contents have moved.
A fair enumeration emits every required occurrence after finitely many computation steps. The inputs can be infinite; completeness does not mean waiting until they have all been exhausted. If two proper lazy lists alternate their next available entries, every occurrence reaches the output after finitely many swaps. In contrast, a nested list comprehension can remain forever in its first infinite inner list. Fairness concerns input occurrences, even when different occurrences happen to have equal values.
For an outer proper lazy list of inner proper lazy lists, introduce row in round and advance each active row once per round. Discard an active row when its terminating constructor is observed. Each round inspects finitely many rows, and the entry at row index , within-row index , is emitted in round . Every earlier round has finite work, proving fair enumeration of all occurrences.
An implementation can keep a finite list of row remainders, append at most one newly introduced row, collect one head from every nonempty remainder, and retain their tails for the next round. It must not first combine all not-yet-introduced rows. In fact, foldr interleave [] ([1,2] : repeat []) can emit 1 and then block before 2; diagonal merging of lazy lists emits both. If infinitely many empty rows remain after the final output, detecting termination is impossible in general: the absence-detection obstruction for infinite lists prevents a universal promise of a terminating empty tail, while every required occurrence can still be emitted.
To find the order statistics at ranks when is a power of two, partition into equal lower and upper rank halves and recurse, stopping at blocks of size . Return each leaf block's maximum. Half boundaries are multiples of , so these leaf maxima are exactly the requested ranks. Linear-time selection gives total partition work per internal level and leaf work, hence overall. The shorter displayed bound applies when .
For deterministic linear-time selection, group keys into fives, compute the median of each group, and recursively select the median of those medians as a pivot. Apart from bounded end effects, at least keys lie on either side. Thus the selection cost satisfies , since the fractions sum to . A strong induction with sufficiently large linear coefficient absorbs the lower-order terms.
Find one specified order statistic without sorting every element. Partitioning about a pivot retains only the side containing the requested rank. Median of medians guarantees a balanced enough pivot to give worst-case linear time complexity.
Pair candidates from a totally ordered set and retain the greater one from each comparison until one winner remains. Every other candidate loses once, so key comparisons suffice to find the maximum of distinct values. A balanced tournament on inputs gives the winner direct losers. Retaining each loser's own defeat record preserves information for finding later order statistics. The comparison records form a rooted tree and are distinct from a graph-theoretic tournament, which includes a directed comparison between every pair.
After a balanced comparison tournament, the second-largest element is the maximum among the winner's direct losers. The third-largest must have lost directly to the winner or to that second-largest element: no smaller element could defeat it. Excluding the known top two leaves at most candidates, because the second-largest won at most earlier comparisons. The three stages use at most key comparisons, proving the displayed bound. Defeat records must retain their earlier subtrees; keeping only the overall winner's direct-loser values discards information used by the last stage.
A selection algorithm that uses array partitioning around a pivot and recursively searches only the side containing the desired order statistic. If there are entries before the placed pivot, an earlier rank is unchanged and a later rank is reduced by . Segment length strictly decreases, proving algorithm termination. The same reduction can update local bounds in a loop, using constant auxiliary space.
Balanced reductions give linear work by a geometric series, while repeatedly discarding only a constant number of entries can give quadratic work. For distinct entries and independent uniform random pivots, a pivot in the middle half has probability at least one half and reduces the retained length to at most three quarters, up to rounding. The expected number of attempts for each such reduction is bounded, so summing expected work over geometric size scales gives expected time. This random-pivot guarantee is not a worst-case guarantee for a deterministic median-of-three heuristic. With duplicates and a strict two-way partition, random pivot choice alone can also fail to shrink an all-equal segment; a three-way partition treats equal keys together.
Choose the median value among the first, middle and last entries of an active array segment. For at least three distinct sampled values, the selected value cannot be the whole segment's minimum or maximum. It can still be the second-smallest or second-largest value, so a balanced split does not follow. Coincident sample indices in segments of length one or two can be handled by the same comparison code. Ties must also have a defined branch policy.
A distinct-input counterexample for Quickselect that chooses the first/middle/last median, reserves it at the last slot, scans lower values to the front, and finally swaps the pivot into place. Let be the following permutation of . For , take increasing order. For , let componentwise and , then set
and put at every other index . These assignments use every entry of once and add zero and one, so they really define a permutation.
The sampled values are , with the last at least two, so the pivot is one. After the initial pivot swap, the only lower value is the zero at index . Moving it to the front places the displaced at its intended tail position. The final pivot swap moves from index one to the last position. Every other tail entry already has its intended position. Thus the complete partitioned result is exactly followed by .
Selecting the maximum consequently repeats the same construction on entries. If counts only pivot comparisons made by the partition scan, then , with and . Hence and total runtime is . For example, . This disproves a linear worst-case claim even when every value is distinct.
To obtain the -th smallest entry of two ascending sorted arrays of lengths , choose prefix lengths with . Search for the two boundary inequalities in the title, treating missing left boundaries as and missing right boundaries as . Then all selected entries precede all unselected entries, so their largest boundary value is the answer. If , decrease ; if , increase . These failures are monotone because one prefix grows as the other shrinks. Binary search thus takes comparisons when the shorter array supplies the searched prefix. Repeated values retain their multiplicities in the ranks.
Deciding whether open real intervals are pairwise disjoint has comparison complexity . Sort by left endpoint and scan the maximum previous right endpoint for the upper bound. For the lower bound, map integer keys to . Such intervals intersect exactly when the original integers agree. Each comparison between endpoints and , with , is determined by a comparison of and their fixed offsets, so the reduction preserves the comparison model. Apply the element distinctness problem lower bound.
Suppose a finite candidate set of size contains the truth, every query chooses a current candidate, and each wrong reply eliminates that candidate while retaining the truth. Then at most wrong queries occur. If a correct reply uniquely identifies the truth, an infinite strategy of this kind eventually repeats the true candidate; stopping when only one candidate remains takes at most replies. The proof is the strictly decreasing positive cardinality of the surviving candidate set after every nonidentifying round.
To score a guess against a fixed-length secret, first reserve every equal-position match. For the remaining positions, consume at most one unused secret occurrence for each cow. This two-stage rule prevents an earlier wrong-position token from using the occurrence needed for a later positional match. The sum of bull and cow counts is the multiset overlap of the two sequences. With only equality tests, deletion from a list gives a quadratic-time implementation; token-count maps can improve the allocation step when a suitable key representation is available.
A quantum algorithm specifies quantum state preparation, a sequence of quantum gates and quantum measurements, and any classical computation controlling them. For a pure quantum state , computational-basis measurement returns with probability , as prescribed by the Born rule. David Deutsch formulated a universal quantum computer using unitary operators and measurement.[ref]
For example, one Hadamard gate prepares . Computational-basis measurement gives either bit with probability . Applying another Hadamard gate before measuring instead gives : the amplitudes for outcome one cancel by quantum interference. This illustrates why manipulating probability amplitudes matters; merely preparing a superposition does not reveal every component.
An analysis of algorithms must state the counted resources: quantum gate count, number of qubits, quantum state preparation cost and repetitions needed for the required probability of a correct result. Quantum query complexity counts quantum oracle calls separately; one such call need not be one elementary quantum gate.
Approximate quantum counting estimates the number of satisfying assignments of a Boolean function, using a quantum oracle and quantum measurement. Controlled repetitions of a Grover search algorithm iteration let quantum interference reveal the count. For one input bit, a Hadamard test can give Pauli Z gate expectation value : with the complemented phase oracle and , use to obtain . Repeated preparations estimate this expectation value; one binary measurement result does not distinguish all three counts .
The Bernstein-Vazirani algorithm identifies the coefficient string of a linear Boolean function with one Boolean quantum oracle call. It contrasts with the calls required by the classical query complexity of linear Boolean function identification. Prepare the data qubits at and an ancilla qubit at , apply a Hadamard gate to every wire, query the function oracle, and apply the Hadamard gates again. The full output is .
The mechanism is Bernstein-Vazirani phase kickback. The Pauli X gate has eigenvector with eigenvalue . Thus the target flips become relative quantum phases on the data, giving
The final Hadamard transform maps this product to , so computational-basis measurement recovers every coefficient with certainty. The ancilla preparation for the Bernstein-Vazirani algorithm ensures the required minus sign, and the Hadamard-conjugated linear oracle gives an exact quantum circuit interpretation. One query is optimal for , since without a query the output cannot depend on the unknown string.
The displayed Bernstein-Vazirani algorithm prepares its ancilla qubit in the computational-basis state before the first Hadamard gate. At the function oracle it is therefore the eigenstate of the Pauli X gate, which enables phase kickback. Preparing instead yields at the function oracle; target flips leave this state unchanged, so the data contain no information about .
The Hadamard-conjugated linear oracle makes the more general statement transparent. With zero data and initial ancilla qubit , the full fixed quantum circuit outputs
For nonzero , the correct data outcome has probability . To obtain exact identification for all , this preparation must have , so it is up to global phase. This is a condition on the prescribed preparation circuit: any alternative quantum state preparation that supplies at the function oracle is equivalent.
Let be the Boolean quantum oracle for a linear Boolean function, and put . The CNOT gates implement , where the data wires control the ancilla qubit. CNOT control reversal in the Hadamard basis and imply the exact unitary operator identity
Here on strings is bitwise exclusive or. To conjugate a product, insert between its factors; each factor reverses its control and target, and the unused Hadamard gates cancel. The global phase is exactly . In particular, the identity holds on arbitrary quantum superpositions, not only on the initialized inputs of the Bernstein-Vazirani algorithm.
A heuristic algorithm uses a selective search or approximation to obtain a useful result efficiently, without a general guarantee of finding the exact optimum.
A sweep-line algorithm processes geometric events in the order a conceptual line crosses a plane. It keeps an event queue and a status describing objects intersecting the current line. For horizontal and vertical line segments, sweep left to right: insert a horizontal segment at its left endpoint, query active heights at a vertical segment, and delete horizontals at their right endpoints. A balanced search structure supports the updates and range reporting. Equal-coordinate event ordering determines whether endpoint contacts count. The method reduces a two-dimensional problem to a changing one-dimensional ordering rather than physically sampling every line position.
The four-sum problem asks whether four selected numbers sum to a target , with the selection rules part of the input specification. In the four-list version, choose one value from each of . Store sums and look for , a meet-in-the-middle algorithm. For lists of length , hashing gives expected time and storage; sorting pair sums gives deterministic comparison-based alternatives. In a single-list version requiring four distinct positions, stored pairs must also satisfy the index-disjointness condition. Equal values and equal positions are different restrictions.
Bit parallelism represents many Boolean states in the bits of a machine word and updates them together with bitwise operations. For example, if a bit at position records whether sum is reachable, adding an item of weight updates the state mask to mask | (mask << w), retaining old sums and adding shifted ones. A fixed-width operation processes up to the word width in parallel. An arbitrary-precision integer spanning many words still costs time proportional to the affected storage; using one language-level integer does not make every operation constant-time.
An algorithm's memory usage is the storage it occupies under a specified accounting convention. Total storage can include input and output, while auxiliary space complexity counts extra working memory; recursion stacks, temporary arrays and cached results must be included when relevant. An iterative binary search needs constant auxiliary storage, but a recursive implementation can keep logarithmically many stack frames. Reporting memory without specifying whether counts bits, elements or machine words can hide a substantial difference. Peak live storage and cumulative allocated storage are also different measurements.
The extra working storage required by an algorithm, excluding the storage occupied by its input. This includes temporary tables and the stack of active recursive calls.
An algorithm's running time is its computational work on an input, measured either as elapsed time on a specified system or as an operation count under a cost model. Time complexity expresses how that count grows with input size. For binary search in a random-access sorted array, halving the candidate interval needs comparisons. The same index-based code on a linked representation need not have that cost. Worst-case, average-case and amortized bounds quantify different questions; a measured duration alone does not prove any asymptotic guarantee.
Rearranging a finite sequence according to a specified order while preserving its entries and their multiplicities. A sorting algorithm performs this operation; lexicographic order supplies a common order for tuples or strings.
Unification finds a substitution making given first-order terms syntactically identical. In first-order unification, a substitution replaces variables by first-order terms while leaving function symbols fixed. A most general unifier captures the necessary identifications: every other unifier follows by a further substitution.[ref]
For example, and have most general unifier . The variable remains free; assigning it a particular first-order term gives a more specific unifier. Requiring forces both and , so distinct constant symbols make it impossible.
Syntactic identity is essential. With addition treated as a binary function symbol, the first-order terms and are different even though their values agree under ordinary arithmetic. Equational unification incorporates specified identities and is a different problem. For finite first-order terms, the occurs check rejects : a finite first-order term cannot equal one of its proper subterms. Unification makes resolution possible by aligning atomic formulas before inference.
Equational unification asks for a first-order substitution making two first-order terms equal under specified identities, rather than requiring them to become literally the same first-order term. Writing for equality justified by those identities, a solution satisfies .
For example, the first-order terms and have no syntactic unifier when are distinct constant symbols and is an uninterpreted binary function symbol. If the specified identity is commutativity, , then the unchanged first-order terms are already equal modulo that identity: the empty first-order substitution is an equational unifier.
The identity set changes the problem. Ordinary first-order unification can decompose equal outer constructors because equality of free first-order terms forces equality of corresponding arguments. Modulo commutativity, argument positions can be exchanged, so that decomposition alone would reject legitimate solutions. A useful implementation must state its identities and its notion of solution, rather than treating equality of interpreted values as syntactic equality.
A unifier of first-order terms is a first-order substitution for which . The first-order substitution replaces variables by first-order terms; it does not alter function symbols. For example, unifies with .
A most general unifier leaves every identification not forced by the original equations available for later choice. For , one solution is . The remaining variable is free. Replacing it by any finite first-order term gives a more specific unifier; arbitrarily choosing during the initial computation would discard that generality.
Not every pair is unifiable. Distinct constant symbols cannot be made equal by replacing variables, and the occurs check rejects for finite first-order terms. These are structural restrictions, not numerical inequalities. Unifiers allow a resolution step to align the relevant atomic formulas before the logical inference is performed.[ref]
First-order unification solves a finite system of equations between first-order terms. A useful rule presentation deletes , orients to when is a variable, decomposes equal outer function symbols into argument equations, and rejects unequal outer function symbols. For , reject a nontrivial occurrence of in by the occurs check; otherwise propagate the substitution through the other equations. A solved system assigns distinct variables that do not occur in its right sides.[ref]
For example,
first becomes . Propagating gives , hence a most general unifier. Keeping without composing the later substitution would leave an unsolved dependency.
The rules preserve the possible unifiers, apart from explicitly rejecting impossible equations. Decomposition works because identical first-order terms have identical constructors and arguments. At a solved system, any other unifier is obtained by instantiating its remaining free variables; this proves the most general unifier property. Efficient implementations share term graphs rather than repeatedly copying growing first-order terms.
A term graph represents the structure of first-order terms with labelled nodes and ordered argument graph edges. For finite acyclic first-order terms, the representation can be a directed acyclic graph, allowing identical subterms to share nodes rather than being copied into separate branches of a tree.
The first-order term has five occurrences in its ordinary syntax tree: one , two and two . A shared term graph can use only three nodes, with the two argument graph edges of pointing to the same node. Sharing a variable node is also useful: identifications made by a unification algorithm can be represented once and followed from every occurrence.[ref]
Sharing changes storage, not the meaning of an acyclic finite first-order term. A cycle is different. A node labelled whose argument points back to itself unfolds to an infinite rational tree; it cannot represent a finite solution to . An implementation must therefore state whether it supports infinite rational trees or enforces the finite-term occurs check.
A rational tree is a possibly infinite tree with only finitely many distinct rooted subtrees. It therefore has a finite representation as a term graph, possibly with cycles. Here “rational” describes finite representability, not values in the rational numbers.
For example, the equation describes the infinite expression . A single node labeled with an edge back to itself represents it. There is no solution among finite first-order terms: the occurs check rejects binding a variable to a first-order term containing that variable. Unification over rational trees instead admits this cyclic representation, so implementations must specify which semantics they use. SWI-Prolog explicitly supports cyclic terms for many term operations.[ref]
The Robinson unification algorithm solves equations between first-order terms by finding a substitution making them identical. Repeatedly delete equal terms, decompose equal function symbols into argument equations, reject incompatible symbols, and substitute a variable by its proposed term. The occurs check rejects for finite-term unification, since no finite term equals a proper term containing itself. For it returns , . Successful finite-term unification yields a most general unifier: every other unifier is obtained by further substitution. Implementations that omit the occurs check instead admit a different cyclic-term interpretation.
A most general unifier is a unifying substitution through which every other unifier factors by a further substitution. It records exactly the equality constraints forced by the terms.
The Bostan-Mori algorithm computes without expanding all preceding coefficients. Work over a commutative ring with a unit; then the quotient defines a formal power series.
Set and . The polynomial contains only even powers. Define
Because the denominator is even, selecting the numerator parity matching proves
Iterate until , then return . With bounded numerator/denominator polynomial degrees , the arithmetic complexity is , where is the cost of multiplying degree- polynomials.
For , the denominator update is . An odd index also multiplies the numerator by , recovering the familiar binary-powering pattern.[ref]
A bitwise operation applies a Boolean operation separately to corresponding positions of binary representations. For four-bit values 1010 and 1100, AND gives 1000, OR gives 1110, and exclusive or gives 0110. Bit shifts move positions, while bitwise complement reverses each bit. The representation width and signedness matter: fixed-width machine arithmetic and unbounded integers need not interpret leading bits alike. These operations are useful for compact sets, flags and bit parallelism. They differ from logical operations that test the truth of entire operands.[ref]
The bitwise complement reverses every bit. In an unsigned width- representation, it sends to for : four-bit 0101 becomes 1010. Width is essential; without a width there is no finite all-ones mask. Python integers instead behave as infinite sign-extended two's-complement values, giving ~x = -x - 1. A width- complement in that setting is (~x) & ((1 << w) - 1). The operation is different from Boolean logical negation, which produces a truth value.[ref]
Bitwise AND combines binary representations position by position, setting a bit exactly when it is set in every operand. For bit masks representing sets, it computes intersection.
Exponential search locates a target's possible range in a sorted sequence by probing indices until the target is bounded above or the sequence ends, then uses binary search inside the final bracket. If the target lies near index , this takes probes under random-access and constant-comparison assumptions. For an unbounded monotone predicate, the same method brackets the first true index. It is useful when the relevant prefix is much shorter than the whole sequence or its length is not initially known. Finite sequences still require bounds checks at each probe.
To discover a positive unknown integer by comparisons, test the thresholds for fixed . If the first threshold not smaller than has index , fewer than candidates remain and binary search needs at most comparisons. Since , the total is at most . Choosing makes the leading constant at most ; the additive constant may depend on .
Exponential sign bracketing finds an integer interval with opposite endpoint signs before sign-bracketing binary search. Suppose is defined on nonnegative integers, its signs can be evaluated exactly, , and for all sufficiently large integers . Test . An exact zero can be returned immediately; otherwise stop at the first positive endpoint and retain the preceding negative endpoint, or zero when .
Excluding the already known evaluation at zero, this takes endpoint tests. For , the final integer interval is , of width . Repeated midpoint tests preserving opposite endpoint signs take further tests to reach adjacent integers, unless an exact zero is found earlier. For , is already adjacent.
No monotonicity is needed to preserve opposite endpoint signs, though other crossings may be skipped. Adjacent opposite signs do not imply an integer root; for , neither endpoint of is a root. A real-valued extension requires continuity to infer a real root by the intermediate value theorem. A machine implementation must handle integer overflow and unreliable floating-point arithmetic; mathematical termination does not ensure representable endpoints.
Coordinate compression replaces coordinates by a smaller representation while retaining the order or distance information needed by an algorithm. Rank compression retains only order; geometry-specific transformations may instead remove known gaps or widths.
The two-pointer technique maintains two indices whose monotone movement avoids revisiting candidate pairs. To find two values summing to in an increasing array, start at its ends. If their sum is too small, move the left index right: every pair using the old left value is too small. If too large, move the right index left by the symmetric argument. Each step eliminates one index, so after sorting the scan takes time. The correctness depends on sorted order; blindly applying the rule to unsorted inputs can discard a valid pair.
The Aho-Corasick algorithm reports occurrences of a finite collection of nonempty pattern strings in one string. It builds an Aho-Corasick automaton from their trie. Each scanned character extends the current state; when no edge matches, failure links find a shorter matching suffix. Report the current terminal pattern string and the terminal ancestors reached through output links.[ref]
The state represents the longest suffix of the scanned text that is a prefix of some pattern string. This invariant explains correctness: a match ending now is exactly a terminal suffix represented by that state or a failure link ancestor. It also reports overlaps. With pattern strings ab, bab, bc, scanning babc reports ab and bab at position three, then bc at position four.
For a fixed-size alphabet, completed transitions and output links give total time, where is total pattern string length, text length and the number of reported occurrences. The term is unavoidable when listing every match. Store terminal output links instead of copying every inherited match list: copied suffix lists can greatly enlarge preprocessing.
An Aho-Corasick automaton augments a trie with a failure link from each nonroot state to its longest proper suffix that is also a trie prefix. Terminal states identify completed pattern strings; an output link points to the next terminal state along the failure link chain. The root represents the empty string. These structures support the Aho-Corasick algorithm.[ref]
For pattern strings ab, bab, bc, the state bab has failure link to terminal ab, so both occurrences are reported after reading bab. If the next character is c, no edge leaves bab on c; following failure links reaches b, whose edge leads to bc. Reporting only the deepest terminal state would miss the simultaneous ab match.
A completed transition table stores the final destination for every state and alphabet character, giving one table lookup per input character. A sparse representation stores only trie edges and follows failure links on demand. They implement the same state invariant; the relevant space and lookup costs depend on the alphabet representation.
An output link in an Aho-Corasick automaton points to the nearest terminal state encountered strictly after the current state on its failure link chain. It skips states that do not end a pattern string. After reading a text character, report a pattern at the current state if terminal, then follow output links to report its terminal suffixes.
For dictionary strings a, ba, aba, reaching state aba reports all three patterns ending at that position. Its output link reaches ba, and the next reaches a. Reporting only aba would miss two valid occurrences. The current state's own match is handled separately because an output link points to a proper suffix, not to itself.
If is the failure link destination, the output link is when that state is terminal, and otherwise the output link of . Build this information in increasing trie depth, so the shorter failure states are already available. Traversing only terminal links makes reporting cost proportional to the number of emitted matches, rather than the length of every nonterminal failure chain.[ref]
The Tonelli-Shanks algorithm finds a square root of a quadratic residue modulo an odd prime number . Handle separately and use the Legendre symbol to reject a quadratic nonresidue. Write with odd, choose a quadratic nonresidue , and initialize
modulo . Maintain , with of multiplicative order and of multiplicative order dividing .
If , find the least with . Set and update
The multiplicative order of decreases because its last nontrivial power and that of are both minus one. Thus strictly decreases. At , the invariant gives .
For , initialization gives . One update gives , so the roots are and modulo thirteen.[ref]
A string-searching algorithm locates occurrences of a pattern in a text, typically requiring a contiguous substring match. For text ababa and pattern aba, zero-based matches start at zero and two; overlaps count unless excluded by the specification. The direct algorithm compares the pattern at each start and can require character comparisons. The Knuth-Morris-Pratt algorithm reuses prefix information for linear total scanning work. State the alphabet, case handling and empty-pattern convention: matching bytes, Unicode code points and user-perceived characters can describe different tasks.
A longest repeated substring is a maximum-length contiguous string occurring at two distinct starting positions in a text. The occurrences may overlap unless a nonoverlap constraint is explicitly imposed. It can be found by comparing all pairs of suffixes, or by taking the maximum longest-common-prefix length of adjacent entries of a suffix array. The latter characterization concerns correctness; the time needed to build the suffix array depends on the construction algorithm.
An FM-index is a compressed text index supporting backward search through the Burrows-Wheeler transform and occurrence counts. Character rank queries locate a matching interval; sampled suffix array positions then allow the actual text positions to be recovered. Query length, number of matches and the chosen sampling density control different parts of the search cost.[ref]
Backward search finds a query's matching interval in a suffix array by processing the query from right to left. With inclusive one-based interval , prepending changes it to . An empty interval means no match. This works through the occurrence-order property of the last-to-first mapping.[ref]
In a sorted cyclic rotation matrix, the last-to-first mapping sends the th occurrence of a character in the last column to its th occurrence in the first column. For one-based rows, , where counts smaller characters and counts in the first entries of the last column. It moves a rotation's start one character backwards cyclically. Equal characters retain the lexicographic order of their following sequences, which proves the occurrence-order rule.[ref]
The Burrows-Wheeler transform appends a unique smallest terminator to a string, sorts its cyclic rotations in lexicographic order, and records the last column. It is reversible because the first and last columns contain the same characters and the last-to-first mapping preserves the occurrence order of each character. The resulting letter arrangement supports both compression and backward search.[ref]
A transition to a shorter suffix match after an attempted extension fails. In a Knuth-Morris-Pratt automaton, the prefix function determines the next shorter matching prefix.
The Knuth-Morris-Pratt algorithm searches for a pattern using its proper prefix-suffix overlaps. After matching characters, a mismatch replaces by the length of the longest proper border of a string for that matched prefix, repeating until the next character can extend it or . The text index never moves backward. Precomputing prefix failure links takes time; during scanning each increase in can pay for a later decrease, giving total character work and auxiliary storage. A dense Knuth-Morris-Pratt automaton is a related implementation with alphabet-dependent preprocessing and storage.[ref]
A Knuth-Morris-Pratt automaton records how much of a fixed pattern matches the suffix of the text seen so far. State means the longest such prefix has length ; reading a symbol moves to the longest compatible prefix state. Reaching state reports a full length- match. For pattern aba, state two records suffix ab; reading a completes the match, while reading b falls back to state zero. A dense table for an alphabet of size uses preprocessing and storage, then constant work per text symbol.[ref]
A border of a string is a string that is both a prefix and a suffix. A proper border is shorter than the whole string; the empty string is often included. The string ababa has proper nonempty borders a and aba. A border of length in a length- string corresponds to an overlap displacement . The Knuth-Morris-Pratt algorithm uses a chain of such borders to decide how much of a partial match survives a mismatch, avoiding comparison of characters already known to agree.
A proper border of a string is a string prefix that is also a string suffix and is shorter than the complete string. With zero-based lengths, its length satisfies for a length- string, if the empty string is allowed. Specify that convention when counting borders.
For ababa, the nonempty proper borders are a and aba; the complete ababa is a border of a string but not a proper one. A proper border of length allows two copies of the string to overlap with displacement . The border aba therefore explains the shift of two between overlapping occurrences of ababa in abababa.
The prefix function stores the longest proper-border length of each prefix. For ababa, following these lengths gives , listing successively shorter candidate overlaps. The Knuth-Morris-Pratt algorithm uses this chain after a mismatch, retaining a suffix already known to match rather than comparing the whole pattern again.
For a string , the value is the length of the longest proper prefix of that is also its suffix. Repeatedly following these lengths lists all proper borders of a string; this is the failure-link information used by the Knuth-Morris-Pratt algorithm.
Redelmeier's algorithm enumerates fixed polyominoes, identifying translations while retaining different orientations. Put the leftmost cell of the bottom row at the origin. Allowed cells lie above the horizontal axis, or on it at nonnegative horizontal coordinates.
Maintain the occupied set of cells, an untried frontier of adjacent cells, and exclusions inherited from earlier branches. Remove a frontier cell , occupy it, and add neighbours newly exposed by . Recurse with a copy of the updated frontier. On returning, undo those new neighbours and remove from the occupied set, but keep excluded from later sibling branches.
The exclusion prevents a later branch from reconstructing a polyomino already assigned to the branch containing . Requiring new cells to touch the occupied set preserves connectivity; every canonical polyomino has a branch determined by its first available frontier choice. Thus each fixed polyomino is visited once.
At size two there are two fixed polyominoes, horizontal and vertical, but one free polyomino after identifying rotations. Counting free polyominoes needs an additional treatment of symmetry.[ref]
Determine whether repeated deterministic updates revisit a state, and optionally find the preperiod and cycle length. Recording all visited states uses memory proportional to the visited orbit. Floyd's cycle-finding algorithm detects repetition with constant extra memory.
For a deterministic iteration with eventual cycle length and preperiod , the Brent cycle-finding algorithm detects repetition using constant auxiliary space.
Hold a checkpoint fixed while another pointer advances through blocks of lengths . At a block boundary, move the checkpoint to the advancing pointer and double the next block length. Compare each new state to the checkpoint. Once the checkpoint lies on the cycle and its block is long enough, the first equality occurs exactly steps after the checkpoint.
To locate the entrance, restart two pointers at the initial state, advance one by steps, then move both one step at a time until they agree. Before index , the first pointer is outside the cycle; at both reach the same cyclic position. The procedure uses evaluations of and constant auxiliary space, assuming constant-cost state equality and copying. An infinite nonperiodic orbit has no finite detection guarantee.[ref]
For a deterministic iteration on a finite set, move one pointer by one step and another by two steps. They eventually meet inside the repeated cycle. Restarting one pointer at the initial state and advancing both by one step locates the cycle entrance; a further traversal measures its length. The method uses constant extra space complexity and time proportional to the preperiod plus cycle length.
A family of algorithms that exploit monotonically changing geometric directions while traversing sorted points or the boundary of a convex polygon. For example, after sorting rays by polar angle around a point, a second index can advance monotonically to identify all rays lying in each open half-plane. Collinear rays require consistent boundary handling.
An algorithm that splits choices into two groups, enumerates partial results for each group, and matches compatible results. For binary choices, the two lists each have about entries instead of enumerating complete choices; the matching cost and memory requirements depend on the problem.
Articles were limited to the first 100 out of 297 total.

Ancestors (2)

  1. Computer science
  2. Home

Discussion (0) New discussion

There are no discussions about this article yet.

Articles by others on the same topic (2)

An algorithm is a finite sequence of well-defined instructions or steps designed to perform a specific task or solve a particular problem. Algorithms can be expressed in various forms, including natural language, pseudocode, flowcharts, or programming code. Key characteristics of algorithms include: 1. **Clear and Unambiguous**: Each step must be precisely defined so that there is no uncertainty about what is to be done.