The Memento pattern supports saving and later restoring an object's state while preserving encapsulation. The originator creates a snapshot and knows how to restore it; the memento stores that snapshot; the caretaker retains mementos and decides when to request restoration, without depending on their representation. Undo history is a typical use.
Scala's nested class in object-oriented programming definitions, access qualifiers, immutable values and path-dependent types help keep snapshots opaque and associated with their originator. For example:
final class Editor {
  private var text = ""
  final class Snapshot private[Editor] (
    private[Editor] val saved: String
  )
  def current: String = text
  def edit(next: String): Unit = { text = next }
  def save(): Snapshot = new Snapshot(text)
  def restore(s: Snapshot): Unit = { text = s.saved }
}

val editor = new Editor
editor.edit("first version")
val saved: editor.Snapshot = editor.save()
editor.edit("later version")
editor.restore(saved)
assert(editor.current == "first version")
The caretaker can retain saved but cannot inspect its private contents or construct an arbitrary snapshot. editor.Snapshot is a type tied to the stable editor value; a snapshot from a different Editor is not interchangeable without an explicit type escape. An immutable string is safe to share in this example. If the originator held mutable arrays or mutable nodes, storing only references to them would not freeze their contents; the memento would need a deep copy or a persistent immutable representation.[ref][ref]
A polynomial-time Turing reduction from a decision problem to a decision problem is a deterministic algorithm deciding membership in in polynomial time when allowed to query whether strings belong to . An oracle Turing machine models each query answer as a single oracle operation, while writing the query and using the answer still costs time. Queries may depend on earlier answers.
For example, the complement of reduces to by asking one membership question and reversing its answer. This is a Turing reduction, regardless of whether there is a simple many-one reduction with the same effect. A polynomial-time many-one reduction instead computes one transformed instance whose answer is used unchanged.
If reduces to this way and has a polynomial-time algorithm, then does too: substitute that algorithm at each oracle call. Polynomially many queries of polynomial length keep the total cost polynomial. Completeness claims must specify which reduction is intended because adaptive access is more permissive.
Proper border of a string 2026-11-05
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.
Pseudorandom generator 2026-11-05
A pseudorandom generator is a deterministic, efficiently computable function with , whose output on a uniform seed is computationally indistinguishable from a uniform -bit string. Its security is relative to a specified class of tests.
For example, suppose a generator maps 128 seed bits to 256 output bits. Its range contains at most strings out of possibilities. Enumerating the range would distinguish it almost perfectly, but requires infeasible work at this size. A secure construction must resist efficient tests that avoid enumeration as well. Merely copying the seed twice fails immediately: a test compares the two halves. Useful generators enable randomized algorithms or cryptographic protocols to expand a limited supply of random seed material.[ref]
Pseudorandomness 2026-11-05
Pseudorandomness means that specified tests cannot effectively distinguish a generated distribution from a genuinely random reference distribution. The allowed tests and their advantage are part of the definition. Passing a few frequency tests does not imply security against every feasible computation.
A pseudorandom generator expands a uniformly chosen -bit seed to bits. For a test , its distinguishing advantage is
Here denotes a uniformly sampled -bit string. There are at most generated strings, so an unrestricted test for membership in the generator's range distinguishes with advantage at least . The useful claim is therefore computational indistinguishability for a restricted test class, not equality of the two distributions. Such a generator can replace random choices in an algorithm when the relevant computation is among the tests it fools.[ref]
Radix sort key encoding 2026-10-18
An encoding for radix sort must make the intended total order of sort keys agree with the lexicographic order of its fixed-width numerical digit tuples. The positional notation for bounded nonnegative integers has this property. At the most significant differing position , a one-unit numerical digit difference contributes , while all lower positions together contribute at most
This geometric series shows why lower numerical digits cannot reverse that comparison. Leading zero padding works here because it preserves place values and the represented integer.
For signed integers in a known integer interval , encode and choose with . This order-preserving function is also injective: exactly when . For , the four-bit encodings of are after adding eight. Restore the original signed sort keys when displaying the complete sorting records; the encoding need not replace their data. Sorting the unsigned values of raw two's complement bit patterns would put nonnegative integers before negative ones, so their representation alone is not this ordered encoding.
For variable-length strings, first specify the alphabet order and whether a proper prefix precedes its extensions. As an original construction, use , let every string have length at most three, encode as one and as two, and append zeros to width three. Zero is reserved for an end marker strictly below every real symbol. The strings encode as in radix three, which preserves their lexicographic order. A differing real symbol decides the comparison; at a prefix boundary, the shorter string's zero comes before the extension's one or two. Left padding would instead encode as and as , reversing . Padding raw bytes with zero also fails if zero is an allowed data symbol: distinct strings can then receive the same encoding. A reserved end marker and an explicit symbol ordering are essential; byte order alone does not establish a desired human text order.
Figure 1.
Stable ties preserve lower digits; suitable encodings preserve the intended order
. Original counterexample above: reversing a tens tie destroys the units order and a later stable hundreds pass cannot repair it. Below: signed integer offsets and a reserved end marker for bounded strings produce increasing fixed-width encodings. All entries are exact constructed examples. Details.
Round-trip testing Created 2026-10-24 Updated 2026-11-05
Test a conversion together with its intended inverse. Equality of representations may need normalization, while equality of numerical values can be limited by floating-point rounding or truncation. Distinct strings can encode the same value, so a value round trip and a character-for-character round trip are different properties.
An independent oracle is still needed: the wrong functions and satisfy both composition identities on integers, although neither implements an intended identity conversion. Thus passing inverse-consistency tests does not alone establish the specification of either conversion.
Separate chaining Created 2026-10-13 Updated 2026-10-20
With separate chaining, each hash bucket in a hash table contains a collection of records, often a linked list. Lookup computes the bucket index, then follows that chain until a key equality comparison succeeds or the chain ends. A hash collision therefore affects the search work without merging unequal keys. Deletion searches the same chain and unlinks the matching record; in a singly linked list, remembering the preceding record during the search permits the unlink.[ref]
For the four-key integer example in hash table, insert a new record at the head of its chain after checking that its key is absent. Inserting in that order makes hash bucket hold , hash bucket hold , and the other two hash buckets empty. All five subsequent operations below select hash bucket because :
Figure 1.
Separate chaining traces lookup, replacement, deletion and insertion through key equality
. Original deterministic model with . The table counts actual keys inspected, not elapsed machine time. Operations occur from top to bottom; only an absent key adds a new record, and the untouched record remains in hash bucket . Details.
get(5) rejects key , accepts key , and returns after two key equality comparisons. get(13) rejects and reports absence after three comparisons. put(5,B*) examines and replaces the value without changing . delete(9) examines just the head record, removes it, and gives . Finally, put(13,E) rejects before inserting the new head record; returns to and the chain is . The successive hash table load factors are . These counts follow from the stipulated chain order; a different insertion policy changes the successful-search counts.
For a chain of length , lookup and deletion by key take time complexity in Big O notation. The same applies to put before any resizing, since replacement semantics require checking for an existing equal key. Head insertion alone is if absence is already known; that is a different precondition. These bounds assume bucket-index hashing, array access, key equality comparisons, allocation and link updates. A long string or large integer can make hashing or comparison depend on its encoded length, so counting record visits alone does not establish constant running time.
Under simple uniform hashing, each distinct key's bucket index is an independent random variable with a uniform distribution on a finite set of indices. The keys and query are fixed independently of this random assignment. Then lookup has expected time complexity, where is the hash table load factor; it is expected when stays bounded. These are model assumptions, not an automatic consequence of using a deterministic hash function.[ref]
Here is the short calculation. For an absent query and stored keys , let be the indicator random variable of . The number of records inspected has expected value
by linearity of expectation. For a present fixed query, scanning its entire chain inspects at most itself plus all other colliding records, with expected value ; stopping at the match only decreases this upper bound. Adding constant hashing and bucket access yields expected for either query. The argument needs pairwise collision bounds; it does not require all the indicator random variables to be independent. A universal hash family can provide a related bound by random choice of a hash function for a fixed key set, as explained in that article.
The worst case remains , and an absent query takes comparisons if all records occupy its hash bucket. For instance, all collide under . Separate chaining remains correct, but a sequence of insertions that each checks the existing chain can take quadratic total work. Amortized analysis of resizing does not remove this search cost, and an adaptive choice of keys based on a known hash function is outside the stated simple uniform hashing model.
String data type 2026-10-24
A type representing a finite sequence of characters or other specified text units. Its indexing and encoding conventions depend on the language. Immutable strings can be shared safely by a saved snapshot because later replacement of a variable does not mutate the saved string's contents.
String prefix 2026-10-25
An initial segment of a string, including the empty string or the whole string. Two strings share a prefix exactly when their initial characters agree up to its length. The longest common prefix is the longest such shared initial segment.
String rewriting Created 2026-10-20 Updated 2026-11-05
String rewriting transforms a string by replacing an occurrence of the left side of a rule with its right side, leaving the surrounding context unchanged. A system may offer several applicable rules or positions, so a reduction need not be deterministic.
For example, changes to and then . A system is terminating if no infinite chain of rewrites exists; it is confluent if any two results reached from the same string can be rewritten to a common result. Together these properties give a unique irreducible normal form. This is useful for deciding equality in algebraic presentations and for implementing symbolic simplification.
String suffix Created 2026-10-20 Updated 2026-10-25
A string suffix consists of all characters from some position to the end of a string. For example, TAC has suffixes TAC, AC, C and the empty string. Sorting these in lexicographic order groups all suffixes beginning with a given query into one interval.
Substring 2026-10-20
A substring is a contiguous segment of a string. It differs from a subsequence, whose selected characters need not be adjacent.
Suffix array Created 2026-10-20 Updated 2026-10-24
A suffix array stores starting positions of a string's suffixes in lexicographic order. All suffixes starting with a fixed query occupy a consecutive interval. This permits string-searching algorithms to search a compact list of positions instead of storing every suffix explicitly.
Suffix automaton Created 2026-10-20 Updated 2026-11-05
A suffix automaton is a minimal partial deterministic finite automaton accepting the suffixes of a fixed string. Every path from its initial state spells a substring; marking every state accepting therefore recognizes all substrings, though that altered automaton need not be minimal for the larger language.
For a nonempty substring , let be the set of positions where an occurrence ends. End-position equivalence groups substrings with the same such set into one state. In ababa, b and ab both end at positions two and four, so they share a state. A character transition extends each represented occurrence; a suffix link leads to the class of the longest suffix outside the current class.[ref]
This represents many substrings with only linearly many states and transitions. The documented incremental construction creates a state for a newly appended character and, when needed, a clone separating incompatible continuation histories. With a fixed finite alphabet it takes time for a length- string. A membership query follows the proposed string's character transitions and fails at the first missing transition.[ref]
Suffix link 2026-11-05
In a suffix automaton, a suffix link from state leads to the state containing the longest suffix of its longest represented string that lies in a different end-position equivalence class. If is the maximum represented length, state represents one string at each length from through . Following links strictly decreases length and eventually reaches the initial state.[ref]
For ababa, the state representing ababa also represents baba; its link leads to the state containing aba. This skips a suffix already in the current class. The links form a rooted tree useful for propagating occurrence counts from longer matches to shorter suffixes.
A context-free language recognized by scanning a string over the alphabet from right to left, counting 0 as and 1 as , and requiring every partial count to remain nonnegative. A context-free grammar with a unique parse tree for each generated string is , . To see uniqueness, reverse the strings: every nonempty nonnegative path either never returns to zero after its first step, or has a unique first return. These two cases determine the production and its component substrings.
Surrogate pair 2026-11-05
A surrogate pair is the two-code unit representation used by UTF-16 for a Unicode scalar value above U+FFFF. The high surrogate lies in D800–DBFF and the low surrogate in DC00–DFFF, written in hexadecimal. They encode one value together; neither surrogate alone is a Unicode scalar value.[ref]
For numerical units , the decoded value is
Thus D83D DE00 gives U+1F600. Swapping the units or discarding one half breaks that encoding. A string operation specified in code units must therefore account for pairs when it intends to preserve complete code points; a grapheme cluster can require still more units.
Trie terminal marker 2026-11-05
A trie terminal marker records that the path to a trie node is a complete stored key, independently of whether that node has children. Store to and top: the node after to must be terminal even though its p child continues to top. Testing only for leaf nodes would incorrectly report that to is absent.
Insertion sets the marker at the end of the key; membership requires both a matching path and a terminal marker. Deletion clears the marker and may prune nodes that have neither a marker nor children. The initial node can itself be terminal if the empty string is a stored key. A symbol outside the key alphabet can implement an explicit end marker instead, but it must be distinguished from ordinary key characters. These conventions separate exact-key lookup from prefix lookup and permit correct enumeration of keys that are prefixes of other keys.
Turing machine encoding 2026-10-31
A finite string describing a Turing machine's states, alphabets, transition rules and designated initial and halting states. Standard encodings have a decidable language of valid descriptions. A syntactic property of an encoding need not be an extensional property of programs; for example, adding an unreachable state changes state count without changing the accepted formal language.