Algorithms: representations, proofs and resource models

This original sequence supplements the preserved six native units, workbook, weighted-path performance and work-order application. It supplies the mathematical and representation mechanisms needed to understand those units without completing a publisher chapter. The older source editions remain available as optional references. All records are fictional. Work aloud or in private notes; exercises, code execution and assessment are optional. A successful test or this written course does not establish professional competence or university credit.

1. Statements, sets, functions and a proof that actually reaches the result

A specification is a mathematical claim about inputs and outputs. A proposition has a truth value once its terms are fixed. “The search is good” has no testable contract; “the returned index is the least i with records[i].customer = target, or None when no such i exists” does. Distinguish a statement about one run from a quantified statement about every valid input. If P means that a list is sorted and Q means that binary search returns a correct insertion boundary, the implication P implies Q makes no promise for an unsorted list. Its converse, Q implies P, is different: one successful search does not prove that the entire list was sorted. A counterexample disproves a universal claim, while many agreeing examples do not prove it.

Negating a quantified claim changes both its quantifier and its predicate. For records already validated to have an ID, the negation of “every pair of distinct records has different IDs” is “there exist two distinct records with equal IDs.” A missing ID is a separate validation failure, not a collision. In a finite audit, a set of previously encountered IDs can witness a duplicate. Equality must be defined: the strings '07' and '7' are distinct unless the contract normalizes them. Normalization itself can create collisions and must precede any uniqueness claim. Conjunction requires both claims, disjunction at least one, and an exclusive choice exactly one. A request can be both missing a required field and carrying an unknown field; code that assumes these error categories are exclusive may fail to report the real record.

A set records membership without multiplicity or order. The sequence [A,A,B] has length three, while its set of values has size two. A multiset retains counts but not positions. A list retains positions and duplicates. Choosing set, multiset or list therefore changes the question being answered, not just the implementation. The union of ID sets asks who appears in either group; intersection asks who appears in both; difference asks who appears in the first but not the second. If A={2,4,7} and B={4,7,9}, their union has four values because |A union B|=|A|+|B|-|A intersection B|=3+3-2. Adding counts without subtracting overlap would double-count two identities.

A function maps each member of a specified domain to exactly one output. The domain matters: a partial lookup from stored IDs to records is not automatically a total function over every string. Return None, a tagged missing result or an error according to the contract. An injective function never maps distinct inputs to the same output. A hash from arbitrary strings into eight slots cannot be injective when more than eight distinct keys are possible: two keys must share a slot. That pigeonhole argument establishes why collision handling is necessary without relying on a particular implementation. A surjection reaches every value in its codomain; that property does not make it collision-free. Composition applies one mapping after another. If canonicalization discards information, hashing or sorting afterward cannot restore the lost distinctions.

Proof methods serve different purposes. A direct argument derives the postcondition from the assumptions. Contraposition proves P implies Q by proving not-Q implies not-P; it must not silently use the converse. Contradiction assumes the negation of a desired conclusion and derives an impossibility. Induction proves an entire family of claims: verify the base case, assume the claim for a precisely identified smaller case, and derive the next case. A recursive function requires a well-founded decrease as well as a correct local transformation. Calling the same function on the same input is not justified merely because the code contains a base case elsewhere.

Consider lower-bound search on a sorted sequence a. Maintain half-open boundaries [lo,hi), initially [0,n). The invariant states that every position below lo contains a value less than x and every position at or above hi contains a value at least x. At each step choose mid=(lo+hi)//2. If a[mid]<x, sortedness establishes the entire prefix through mid is less than x, so lo=mid+1 preserves the invariant. Otherwise hi=mid preserves the suffix claim. When lo=hi, those claims cover the whole array and identify the first position at which x could be inserted. The nonnegative integer hi-lo strictly decreases, proving termination. Access is made only while lo<hi, so mid is a valid position. Empty input starts with equal boundaries and returns zero without indexing anything. This proof connects the update, the input precondition and the final answer; “it halves the list” alone does not.

Worked mathematical record

Fictional requests have IDs [12,12,19,25]. The task is to return every matching position for target12, not every distinct ID. Before processing position i, let output equal exactly the matching positions in the prefix a[0:i]. Initially both the prefix and output are empty. Processing a match appends i; processing a nonmatch leaves output unchanged. At i=4 the invariant yields [0,1]. Converting input to a set first would lose the second occurrence and its position. If the postcondition instead asks whether any match exists, early return is valid after the first match and the invariant can be weaker. Specifications determine which proof and representation are appropriate.

Optional foundation practice: negate “for every requested ID there is exactly one current record.” Optional changed facts: the data source can contain duplicate IDs with different content. Give a validation policy before selecting an index.

Model reasoning: failure can mean at least one requested ID has no current record, or at least one has more than one. A dictionary assignment that overwrites earlier values would conceal the second case. Scan the source, maintain an ID-to-record mapping and reject a repeated ID whose existence violates the contract, retaining the conflicting source record for inspection. If exact duplicates are intentionally idempotent events, require a separately specified identity-and-content rule. Do not let equality of one field authorize silent replacement of the whole record.

Counting, recurrence and induction preparation

The product rule counts successive choices only after their dependence is specified. Three independent positions with two symbols each give 2^3=8 strings. Three positions chosen without replacement from five distinct IDs give 5*4*3=60 ordered selections. If order is irrelevant, each three-element set was counted 3!=6 times, so there are 60/6=10 sets. A selection with replacement follows a different count. These distinctions matter when constructing test inputs: all permutations, all subsets and all repeated sequences are not interchangeable coverage claims.

A recurrence relates a quantity to smaller instances. If a scan performs one operation per item, T(n)=T(n-1)+1 with T(0)=0 yields T(n)=n. For a balanced merge sort on n=2^k, T(n)=2T(n/2)+n with T(1)=0. Each of k levels has total merge work n, so T(n)=n*k. Induction checks this: assuming the formula for n/2, 2*(n/2)*log2(n/2)+n=n*(log2 n-1)+n=n log2 n. The formula is an operation model, not an elapsed-time prediction. When subproblems overlap, counting the recursion tree without memoization can be very different from counting distinct cached states. When arithmetic operands grow, a unit-cost model for every integer operation can also fail.

Optional changed recurrence: divide into two equal parts but do constant combining work, T(n)=2T(n/2)+1, T(1)=0. Model: the tree has n leaves and n-1 internal nodes, giving n-1 combining operations. Equivalently induction gives 2*(n/2-1)+1=n-1. The same branching pattern does not imply the same n log n cost; the work at each node matters.

2. Arrays, links, deques and paying for movement

An abstract interface describes permitted operations; a representation determines their costs and invariants. A stack supplies last-in first-out push/pop. A queue supplies first-in first-out enqueue/dequeue. A list adds indexed access and insertion. A dictionary maps keys to values. A dynamic array can support several interfaces, but that does not make every operation constant-time. Its backing storage has a capacity C and a live length n with 0<=n<=C. Reading index i uses address arithmetic under a random-access model. Inserting at i must shift the suffix one place to avoid overwriting an element. Move from the end toward i; moving in the opposite direction would repeatedly copy the newly overwritten value. Removing at i shifts the following elements left and clears the no-longer-live final slot when reference retention matters.

When capacity is exhausted, allocate a larger backing array and copy the live elements. Starting with capacity one and doubling, the copies before m appends are bounded by 1+2+4+... below 2m. The m ordinary placements add m, so total movement is less than 3m in this simplified model. That establishes constant amortized append cost for the sequence, not constant worst-case latency for each append. The resize that copies a million elements remains expensive. Increasing capacity by exactly one each time instead copies 1+2+...+(m-1)=m(m-1)/2, so amortized behavior becomes linear per append. Capacity policy is part of the analysis.

Shrinking can create oscillation. If an array halves as soon as it is half full, an alternating insertion/removal near the boundary can repeatedly copy a large array. Leave slack: for example, double on full capacity and halve only when live size falls to at most one quarter, with a minimum capacity. After a shrink the array is near half full, leaving many ordinary updates before another resize. The different thresholds create room to charge future rebuilds to intervening operations. This does not remove the cost of shifting for arbitrary middle insertion.

A circular queue keeps a start offset j and live length n; logical position i is stored at (j+i) modulo C. Dequeue advances j rather than shifting every remaining value. On resize, copy live entries in logical order and reset j to zero. Worked record: capacity5, j=3 and n=3 store logical [A,B,C] at physical slots3,4,0. Removing A changes j to4,n to2. Appending D writes at (4+2)%5=1, producing logical [B,C,D] across physical4,0,1. A loop that copies physical slots0,1,2 during resize would produce the wrong order. Copy by logical position.

A deque permits both ends. A circular-array implementation can insert near the nearer end by moving a shorter prefix or suffix, giving movement proportional to min(i,n-i), plus amortized resizing. A dual-array deque stores a front portion reversed and a back portion forward. Access maps the front index through reversal; rebalancing redistributes when one side becomes much larger. Rebalancing must reverse the appropriate portion, not concatenate its raw physical order. Rootish storage divides the sequence into blocks of sizes1,2,3,... . The first b blocks hold b(b+1)/2 elements, so b is on the order of sqrt(n). The logical index determines a block from triangular-number boundaries; integer checks around an approximate square-root calculation avoid floating-point boundary errors. Unused final-block space and the block-pointer array are both on the order of sqrt(n). It reduces excess space relative to a single geometric array but adds indexing and allocation complexity; it does not make arbitrary insertion free.

Linked nodes store values and references rather than adjacent array positions. A singly linked node points to its successor. Inserting after a known node p requires setting new.next=p.next and then p.next=new; reversing these assignments can lose the old suffix or create a self-link. Removing after p bypasses its successor, with special handling for a tail pointer. Finding p from an integer index still requires traversal. A doubly linked node also stores prev. To insert x between p and q, connect x.prev=p, x.next=q, p.next=x and q.prev=x. A circular sentinel simplifies empty/end cases, but the invariant that successor/predecessor links agree must hold after every operation. A handle to an already removed node must not be accepted as though it remained part of the list.

An intrusive list can provide constant-time removal given a valid node handle, while an array provides direct indexed access and compact traversal. Their tradeoff depends on the actual workload, allocation overhead, locality and handle lifetime. “Linked lists have fast insertion” is incomplete without identifying whether the insertion location is already known. An XOR or doubly linked representation does not eliminate the need to locate the node or manage ownership.

Worked update and changed representation

An initially empty dynamic array has capacities1,2,4,8 as it accepts five appends. Resizes copy1+2+4=7 existing entries; placements write five entries. A subsequent insertion at index1 with five live entries shifts four, independently of unused capacity. If the five values are instead in a singly linked list, insertion after the head changes two references, but insertion at index4 first traverses from the head. Count locating and changing separately.

Optional transfer: a queue receives one million events and repeatedly removes its first entry using a conventional dynamic-array front deletion. Model: each deletion shifts the remaining suffix; draining costs (n-1)+(n-2)+...+0, or n(n-1)/2 moves. A circular queue or a deque changes the representation so front removal adjusts an offset or links. It does not justify reclassifying the existing shifting implementation as constant-time. A memory budget or strict per-operation deadline may also favor segmented storage or explicit capacity limits over occasional large copies.

3. Hashing and randomized search structures

Hashing separates key equality from slot choice. A hash function maps a key to a numerical value; a table maps that value into a finite bucket range. Equal keys must receive compatible hashes within the structure's lifetime. Unequal keys can collide. A mutable field used in hashing must not change while the object remains stored under its old hash, or later lookups can search the wrong bucket. A dictionary of customer-to-order-lists also needs a business identity rule: two equal customer names are not necessarily the same customer, and two order IDs with conflicting payloads must not be silently merged.

Separate chaining keeps a collection at each bucket. Lookup computes the bucket and compares keys in it. With n keys, m buckets and a suitable distribution, expected chain length is n/m; controlling this load factor supports expected constant lookup. An adversarial or poor hash distribution can put everything in one bucket and make lookup linear. The expectation must identify the randomness or input model. Resizing allocates a new table and rehashes entries because the bucket modulus changed. Moving bucket arrays without recomputing placement breaks lookup.

Linear probing stores keys in the table itself. Starting at h(key), inspect consecutive slots modulo capacity until the key or a never-used slot is found. A never-used slot ends unsuccessful search because insertion would have stopped there. Deletion therefore cannot simply turn an occupied slot into a never-used slot. Use a tombstone or repair the cluster. A tombstone does not end lookup, but insertion can reuse its first encountered position while still checking for an existing equal key. Track live occupancy and used-slot occupancy separately: a table with few live keys but many tombstones can still have long searches and needs rebuilding.

Worked record: capacity7, h(k)=k mod7, insert10,17,24. All hash to3 and occupy3,4,5. Delete17. If slot4 becomes never-used, lookup24 stops there and reports absence incorrectly. With a tombstone at4 it continues to5. Insert31, also hashing to3: remember4 as reusable, continue to ensure31 is not already farther along, then place it in4 once a genuine empty slot ends the search. If every slot is occupied or tombstoned, a bounded full-cycle rule is necessary; an unbounded loop waiting for an empty slot can fail to terminate. Load thresholds and rehashing make that state avoidable under the intended contract.

Cuckoo hashing gives each key two candidate slots in separate tables. Insertion can evict a resident, move it to its alternate slot and continue. Lookup examines a bounded number of candidates, but insertion can encounter a cycle and must stop after a defined displacement budget, rebuild with new hash choices or grow. A cycle is not evidence that the key is absent. Randomization gives a probability model for performance, not permission to discard a displaced key. Multiplicative or tabulation-style hashing chooses a family of mappings; the assumed independence properties must match the analysis; a claim about pairwise collisions is not automatically a claim about every dependent probe sequence. A fixed identity-modulus toy hash is useful for traces but not evidence of adversarial robustness.

A skiplist maintains an ordered bottom-level list and selected higher-level shortcuts. Generate each new tower height by independent promotion trials, so a height of at least k has probability about 2^-k under fair promotion. Search begins high, moves right while the next key is less than the target, then descends. Insert records the predecessor at every level and splices the new tower into those levels. Delete bypasses it on each occupied level. Expected logarithmic traversal and expected linear total tower nodes follow from the geometric height distribution and search analysis; worst-case towers or gaps can still be unfavorable. Duplicate policy and comparator consistency remain necessary.

Binary search trees preserve ordered subtrees: every key in the left subtree is less than the node's key and every key in the right is greater, with an explicit alternative rule if duplicates are retained. Search follows that order. Inorder traversal yields sorted keys. A rotation changes the shape while preserving inorder order. For a right rotation at y with left child x, x becomes the local root, y becomes x's right child, and x's old right subtree becomes y's left subtree. All its keys were between x and y, so this relocation respects both boundaries. Update the old parent's link, child-parent links and any stored sizes/heights; a correct key diagram with stale metadata can still break rank or balancing operations.

A treap assigns a distinct random priority to each key, preserving binary-search order by keys and heap order by priorities. Insert by key, then rotate the new node upward while its priority outranks its parent. With priorities independent of keys, the induced shape corresponds to a randomized search-tree model and has expected logarithmic search depth. A fixed priority derived predictably from the ordered key can destroy that assumption. To remove a node, rotate an appropriate higher-priority child upward until the node can be removed, or merge its two treaps under the heap rule. A rotation preserves key order but must also be chosen to restore priority order.

Optional changed facts: a service requires a strict worst-case search deadline, and the only evidence offered is average skiplist search length under one seed. Model: that experiment neither proves the expected bound under the intended randomness nor establishes a worst-case guarantee. Choose a deterministically height-bounded structure, or explicitly bound/mitigate the randomized tail risk. Preserve reproducible seeds for debugging without confusing a fixed experimental seed with a universal performance argument.

4. Balancing, priority queues and integer order

An unbalanced search tree can become a chain after increasing-key insertion. Its interface remains a dictionary, but search can visit every node. Balancing controls shape. A scapegoat-style tree records a size bound and detects insertion depth beyond a logarithmic threshold. Along the deep path, find an ancestor whose child subtree contains more than a chosen fraction, such as two thirds, of its nodes. Rebuild that ancestor's subtree by inorder traversal and repeated median selection. The rebuild costs linear work in that subtree's size. Many updates are required to create the same imbalance again, supporting an amortized update argument. Search benefits from a bounded height; one rebuilding update can still be expensive. Deletions require a global shrink/rebuild policy so the historical size bound does not drift arbitrarily above current size.

A red-black tree uses color constraints to bound height without whole-subtree rebuilding. Specify a conventional variant: the root and absent leaves are black, a red node has black children, and every path from a node to an absent leaf contains the same number of black nodes. Red links cannot form consecutive chains, so a longest path is at most about twice the black-height. Here black-height b counts internal black nodes on a root-to-absent path and excludes the absent leaf. A subtree of black-height b contains at least 2^b-1 internal nodes, yielding logarithmic height. Insertion creates a red leaf: black-height initially remains equal, but a red parent can violate the no-consecutive-red constraint. With a red uncle, recolor parent and uncle black and grandparent red, then continue upward; with a black uncle, a triangle is first rotated into a line, then rotate the grandparent and recolor to remove the local red-red conflict. Finally restore a black root. Deletion of a black node can create a black-height deficit; sibling color and sibling-child colors determine rotations/recoloring that move or discharge the deficit. A complete implementation must implement and test those cases rather than merely recolor every new node black, which would create unequal black-heights.

Worked insertion: starting black root10 with red children5 and15, insert1 under5. The new red1 has red parent5 and red uncle15. Recolor5 and15 black, make10 red, then restore root10 black. Paths through either subtree retain equal black count. In contrast, insert30,20,10 into an initially empty conventional red-black tree. After30 black and20 red, inserting10 creates an outer red-red chain with a black absent uncle. Rotate right at30 and recolor20 black and30 red; root20 has red children10 and30. The ordering remains10<20<30. These are insertion traces, not a complete proof or a complete deletion implementation.

A binary min-heap is a complete binary tree commonly stored in an array. Children of index i are2i+1 and2i+2; parent is floor((i-1)/2). Its invariant requires a parent's priority no greater than its children's, not global sorted order. Insertion appends at the next complete-tree position and swaps upward until heap order holds. Remove-min takes the root, moves the final entry to the root, shortens the array and swaps downward with the smaller child. Choosing the larger child can leave the smaller child above a greater parent. Each repair follows one height-bounded path, giving logarithmic worst-case work. Bottom-up heap construction sinks internal nodes; many nodes are near leaves, so summing their possible distances yields linear total construction rather than n log n.

Worked heap: insert priorities [9,4,7,1]. After9: [9]; after4: [4,9]; after7: [4,9,7]; after1: append[4,9,7,1], swap with9 then4, yielding[1,4,7,9]. Remove-min moves9 to root and sinks under4, producing[4,9,7]. That array is a heap but not a sorted list. With equal priorities, attach a monotone tie-breaker if payload objects are not comparable. The heap should not unexpectedly compare arbitrary payloads when priorities tie. A meldable heap instead joins heap-ordered pointer trees, often using random choices while recursively melding along a selected child. Analyze the corresponding expected recursion and acknowledge that it is not the same representation or guarantee as the binary array heap.

Counting sort exploits a bounded integer key range rather than only comparisons. Count occurrences in K buckets, turn counts into cumulative positions, then distribute records into output. For stable output, a conventional implementation scans input right to left and decrements each key's cumulative end position before placement. Equal-key records then retain original relative order. Work is O(n+K), memory includes K counters and output. If keys range over billions but only five records exist, initializing the whole range is inappropriate. Comparison-sort lower bounds do not prohibit counting sort because its operations and key assumptions differ.

Least-significant-digit radix sort applies a stable distribution by successive digit positions. For [21a,13,21b,12], a stable units pass gives [21a,21b,12,13]; a stable tens pass gives [12,13,21a,21b]. Reversing equal-key records in the tens pass could destroy the lower-digit order established earlier. With d digits in base b, counting passes cost O(d*(n+b)); the bound depends on word width and digit choice. Signed integers need an explicit ordering transform or sign-aware partition; applying unsigned bit order blindly places negative values incorrectly. Variable-length strings require end-of-string ordering, not merely padding them with an arbitrary character that might also be real data.

A binary trie follows the bits of fixed-width unsigned integers. With width w, each key occupies a root-to-leaf path of w bit decisions, so simple search takes O(w), not automatically O(log n). For keys0011,0101,1100, a query0110 follows0 then1 and lacks the next1 branch. The largest stored key below0110 is0101 and the smallest above is1100. Finding those neighbors requires an appropriate neighboring subtree or maintained leaf links; the prefix01 is not itself a stored whole key. Compression can merge degree-one paths, retaining their bit ranges for verification. For predecessor/successor queries, an x-fast-style structure stores prefixes in hash tables by depth and binary-searches for the longest present prefix, combining expected hash lookup with logarithmic-in-w depth search and extra space. A y-fast-style design keeps sampled representatives in that structure and smaller ordered groups for the remaining keys. These mechanisms explain the tradeoff; they do not justify treating every integer-trie implementation as having the same bound, space or assumptions.

Optional transfer: keys are 256-bit cryptographic identifiers and n=40. Model: a simple bit trie can require up to256 bit steps per lookup, while a balanced comparison tree takes logarithmically many comparisons but each comparison has a bit cost. Hashing likewise reads key material. State whether key operations are unit cost or proportional to width, then compare the actual workload and memory. “Integers are constant-time” is a machine-model assumption, not a property of arbitrary-length mathematical integers.

A deletion repair is more than a balancing label

For conventional red-black deletion, first reduce the structural removal to a node with at most one non-absent child; for a two-child key, transplant its inorder successor while preserving the appropriate structural color bookkeeping. Removing a red leaf changes no path's black count. Removing a black node with a red child can replace it by that child colored black. The difficult case removes black without such a red replacement. Think of an extra black owed at the replacement position, including an absent-leaf position with an explicit parent. Keep that parent even when the replacement has no ordinary node object.

Suppose the deficient position x is the left child, with sibling w on the right. The mirror cases exchange left and right. If w is red, its parent is black and w's children are black. Recolor w black and the parent red, then rotate left at the parent. This transforms the situation into one with a black sibling; it does not itself discharge the missing black. Recompute the sibling reference after rotating. If that black sibling has two black children, color the sibling red and move the deficit to the parent: the sibling side gives up one black to match the deficient side. A red parent can absorb it by becoming black; a black parent can require further repair upward. Color conventions for absent children must be explicit, and the valid-tree black-height invariant constrains which absent-sibling cases can actually arise.

If a black sibling has a red near child (its left child in this orientation) but a black far child, recolor/rotate the sibling to obtain a black sibling with a red far child. Finally give the sibling the old parent color, color the parent black and the far child black, and rotate left at the parent. The repaired subtree restores equal black-height while preserving key order, and the deficit is discharged. If the deficit reaches the root, it can be removed because every root-to-leaf path loses the same extra black. These cases explain the mechanism and the termination measure—moving the unresolved deficit upward or finishing locally. They also explain why a generic “rotate until balanced” loop is inadequate: a rotation without the required color changes can preserve sorted traversal while corrupting black-height.

Optional worked deficiency: black root10 has black leaf children5 and15. Delete5. At the absent left position, sibling15 is black with two black absent children. Recolor15 red and move the deficit to10; reaching the root discharges it. The result is black10 with red right child15. Both root-to-absent paths have equal black count. If15 instead had a red right child20 before deletion, the far-red case rotates15 to the root, colors10 and20 black and finishes locally. Sorted order alone cannot distinguish a correct result from a color-corrupted one, so a validator must check root color, red-parent constraints, equal black-height, parent links and ordered ranges.

5. External memory and a cumulative Cedar work-order record

When a dataset exceeds memory, moving a block can cost far more than comparing keys already cached. Define an external-memory model with blocks holding B records and a fast-memory budget M records. A sequential scan reads on the order of n/B blocks. A pointer-based binary tree can cause one block transfer per level if nodes are scattered. A multiway B-tree stores many ordered separators and child pointers per node so one block fetch chooses among many subranges. Its high fanout lowers the number of block levels. The asymptotic I/O argument does not mean that comparisons inside the block are free in elapsed time; it deliberately separates the expensive resource being counted.

For a conventional minimum degree t>=2, a nonroot B-tree node holds between t-1 and2t-1 keys and, if internal, one more child than keys. All leaves have the same depth. Root exceptions permit a small tree. Before descending into a full child during insertion, split it around its median: promote the median to the parent, put the lower keys/children in one node and the upper keys/children in another, then descend into the appropriate half. The split preserves ordered ranges and equal leaf depth. If the root is full, create a new root and split the old one, increasing every root-to-leaf path by one. During deletion, avoid descending into an underfull child by borrowing a separator through the parent from a sufficiently populated sibling or merging with a sibling and the separating parent key. A merge can propagate a deficiency upward; an empty internal root can be replaced by its sole child. Root handling and child ownership are essential to the invariant.

Worked t=2 insertion: insert10,20,5 into one leaf, giving[5,10,20], now full. Before inserting6, split the root: new root[10], children[5] and[20]; insert6 into the left leaf to get[5,6]. Insert12 and30 into the right leaf to get[12,20,30]. Before inserting17, split that child, promoting20: root[10,20], leaves[5,6],[12],[30]. Insert17 into middle leaf, producing[12,17]. Every leaf remains at depth one, and the separators delimit the three ranges. Searching19 visits root then middle leaf and reports absence; searching20 finds the separator in this B-tree variant. A B+ tree instead stores records at leaves and uses internal separators for navigation; copying a B-tree deletion rule into a B+ tree can therefore mishandle record ownership.

The whole structure is not an atomic durable database merely because it has balanced pages. A crash between writing a child split and its new parent can leave unreachable or multiply referenced pages. Real persistence needs an explicit logging, copy-on-write or transactional page protocol, recovery rules and concurrency control. This course's paper trace models ordered access and block movement, not a production storage engine. Benchmark cold and warm cache separately, include construction and update work, and avoid presenting a RAM-only timing as evidence of disk I/O behavior.

The system around the algorithm

A processor executes instructions using registers and a hierarchy of caches before main memory. Spatial locality makes adjacent-array traversal attractive; a linked traversal can require fetching unrelated cache lines. A cache miss is not a change in the logical algorithm, but it changes the machine work required per logical step. Two linear scans can therefore have different measured times without either ceasing to be linear in the chosen model. A word-RAM analysis assumes bounded-size words and certain constant-time word operations. Python objects and unbounded integers add representation overhead; a reference array is not necessarily a packed array of numeric values.

A process owns an address-space context and resources; threads within a process share much of that state. The operating system schedules runnable work and suspends work waiting on I/O. More runnable threads than available cores do not create additional cores. Context switching, synchronization and contention can make additional concurrency slower. In a virtual-memory system, a process's virtual address is translated through page mappings; a missing resident page can trigger much more costly backing-store work. Allocating a large index can therefore change not only memory consumption but the residency and behavior of the rest of a workload. Report the total working set, not merely the size of one result variable.

Shared-state updates need an ordering rule. Suppose two workers both read counter0, independently add1 and write1. The final counter is1 although two events occurred. The arithmetic is correct inside each worker; the combined read-modify-write operation was not indivisible. A lock or suitable atomic operation must cover the whole critical update, and every participant must follow the same protocol. For a source-plus-index change, locking only the index leaves a window in which readers can combine different source and index versions. An immutable snapshot with a versioned pointer, or a transaction over the relevant state, supplies a different consistency boundary. A process-local lock cannot coordinate unrelated processes unless they share an appropriate lock service or storage contract.

Network communication adds another boundary. An application serializes a request into bytes, the transport moves a byte stream or datagrams according to its protocol, and the receiver parses it under a schema. A byte stream does not preserve application message boundaries: a read may contain part of a message or several messages. Use a length, delimiter with escaping, or another explicit framing protocol. Validate the length before allocating an unbounded buffer, reject malformed fields and define character encoding. A well-formed request is not automatically authorized, and a fast query must not return another account's data merely because its key was guessed.

A timeout means the caller did not obtain a timely confirmed response. It does not prove that the receiver performed no work. For a read-only query, retry behavior differs from retrying a state-changing operation. A state-changing operation can use a stable request identity bound to its payload, with a receiver-side record preventing conflicting duplicate effects. The whole design depends on the receiver's actual persistence and lookup contract. An in-memory set lost on restart does not establish durable idempotency. This course's fictional work-order examples are for local practice and must never be pointed at real learner or customer tables as a test.

Worked resource record: a service receives200 requests per second, while its single worker completes150 per second under the stated fixed conditions. After10 seconds of sustained input, backlog increases by500 requests, ignoring initial transient variation. A faster dictionary lookup that changes worker capacity from150 to160 still leaves400 added requests over those10 seconds. The bottleneck might be serialization, database access or scheduling rather than key lookup. Bounded queues, backpressure or capacity changes address the system; an unbounded queue merely postpones the failure while consuming memory. If a serialized response has50000 records, expected constant key access does not make transmission constant-time. Define what happens when the queue is full, and measure end-to-end latency and error behavior alongside isolated lookup time.

Optional changed facts: the average offered rate is100 requests per second but arrivals come in short bursts of10000. Model reasoning: a long-run average below service capacity does not bound the maximum queue or individual latency. Specify burst assumptions, queue limits, rejection/retry behavior and the acceptable service deadline. A benchmark that spreads arrivals evenly tests a different workload. Likewise distinguish successful recovery from a retry that duplicated a committed effect. These are system assumptions surrounding the algorithm, not reasons to abandon precise algorithmic analysis.

Complete cumulative investigation

Cedar has six fictional work orders in source order:

IDCustomerPriorityDependency
W1A21none
W2B13W1
W3A21W2
W4C12W1
W5A5W4
W6B30W3

The contract requires unique immutable order IDs, exact customer equality, source-order results within each customer, and stable increasing-priority output. Dependencies are prerequisite-to-dependent edges, so W1 points to W2 and W4. Optional task: specify the source of truth, build a customer index and stable priority view, find all priority21 orders, traverse dependencies from W1, then evaluate a proposed update and representation choice. Include missing IDs, a duplicate-ID conflict and a cycle. Work entirely with this fictional record; no Academy learner record is involved.

Complete model: validate all IDs before building secondary structures. The customer index is A->[W1,W3,W5], B->[W2,W6], C->[W4]. Stable priority order is W5,W4,W2,W1,W3,W6. For key21, lower and upper boundaries in the priority array are3 and5, so the slice contains W1,W3 and retains their relative order. A hash index answers customer equality; a sorted priority array answers ordered boundary queries. Neither automatically answers the other's question. With adjacency lists W1:[W2,W4], W2:[W3], W4:[W5], W3:[W6], breadth-first discovery from W1 gives W1,W2,W4,W3,W5,W6. The discovered/parent map prevents repeat expansion, but finding a directed cycle requires a separate argument such as active-path state in depth-first traversal or topological indegree elimination; an ordinary visited set alone does not distinguish a back edge from a shared descendant.

Change W3's customer fromA toC. A source-only update leaves the old index incorrectly returning W3 forA and omitting it forC. A coherent update validates identity, removes W3 fromA's ordered list, updates the canonical record, inserts W3 intoC's list at the correct source-order position and invalidates/rebuilds dependent snapshots under one stated consistency boundary. The resulting lists are A:[W1,W5], C:[W3,W4]. Appending W3 afterW4 would violate the source-order contract even though membership was correct. A new event labeledW3 with a different priority must be rejected as a conflicting creation, or handled through an explicitly versioned update operation; unconditional dictionary overwrite is not an identity policy.

Add dependency W6->W1. The path W1,W2,W3,W6,W1 is a directed cycle, so no topological execution order exists for that component. Reachability is still a meaningful query. If dependency costs are introduced, BFS minimizes edge count only under that objective; it does not minimize arbitrary total weight. Use the preserved nonnegative weighted-path performance argument when its assumptions hold, and reject or choose a different algorithm when they do not. Do not let a successful query for W5 conceal a cycle elsewhere in a requested all-orders execution schedule.

For a stipulated cost model with n=4096, log2 n=12, preprocessing a sorted snapshot costs n log2 n=49152 comparison units. Each boundary query costs12 units, ignoring output. A scan costs4096 units per query. With q queries, indexing wins when49152+12q<4096q, or q>49152/4084, approximately12.035; the first integer is13. Atq=12, scans cost49152 while indexed work costs49296; atq=13, scans cost53248 while indexed work costs49308. This model assumes a static snapshot, equal abstract comparison costs and no output/maintenance cost. A return of k matches adds at least proportional output work regardless of how quickly their boundary was found.

Changed workload: every query is preceded by an update that rebuilds the entire sorted snapshot. Then indexed work is q*(49152+12), which exceeds q*4096 for every positive q under the same toy model. A dynamically maintained balanced structure changes that maintenance model but adds its own comparison, allocation and consistency costs. An out-of-memory dataset changes the dominant resource to block transfers; a B-tree or other page-oriented representation can be appropriate even when the in-memory comparison model favored another structure. A hostile hash distribution changes expected lookup behavior; a service with a worst-case deadline cannot rely only on an average hash lookup claim. These changes call for a revised specification and cost argument, not a new favorable timing selected after the fact.

Optional cumulative rubric

Use six dimensions, each0–4, for private self-appraisal. Four requires the evidence described; three means a minor omission while the inference remains sound; two means partial correctness with a consequential gap; one means labels or unsupported results; zero means absent or contradictory work. The total24 is feedback, not verified mastery or an award.

DimensionEvidence for four points
Contract and mathematical preparationDefines identity, equality, ordering, quantified claims and the changed operation; distinguishes sets, sequences and duplicate events.
Representation and invariantsTraces array/link/hash/tree mechanisms and validates structure-specific invariants, including collision/deletion or balance/page cases.
Correctness and terminationConnects initialization, preservation and termination to postconditions; distinguishes directed-cycle detection, reachability and weighted objectives.
Costs and workloadDerives the13-query crossover, includes construction/output/update costs, and states expected/amortized/worst-case and RAM/I/O assumptions.
Evidence and implementationUses independently calculated expected records and boundary cases, checks answer equivalence before timing, and reports limitations of finite tests.
Changed facts and integrationCorrectly revises customer order, rejects conflicting identity, diagnoses the cycle and revises the representation after update/I/O/adversarial changes.

Before totaling, identify the weakest invariant or assumption. A fast implementation that returns stale W3, silently overwrites identity or invents an acyclic schedule needs substantive correction regardless of its other scores.

Optional references and study route

Work through sections1–3 alongside native units1–2, integer-order material alongside unit3, balancing/heaps alongside unit4, and the cumulative/resource material alongside units5–6. The preserved workbook, weighted-path model, integration project and complete application supply additional original cases. All source reading and all practice are optional; no publisher chapter is a prerequisite to using this teaching.

Optional source references: Pat Morin, Open Data Structures, https://opendatastructures.org/ods-python/ (representation and analysis reference); Oscar Levin, Discrete Mathematics: An Open Introduction third edition, https://discrete.openmathbooks.org/dmoi3.html (mathematical reference); Python bisect documentation, https://docs.python.org/3/library/bisect.html (boundary and insertion behavior). These references do not establish that the Academy implementation has their properties. The exposition, Cedar record, proof examples, changed cases and rubric above are original Academy instruction. Independent subject review and observed learner testing remain pending.

Optional references: Open Data Structures · Discrete Mathematics, third edition · Python bisect documentation

Inspect the complete resource-safe laboratory source and execution boundary