Lazy data structures
Overview
Kent Quanrud explains amortized analysis as a deterministic guarantee over operation sequences, not an assumption that inputs are random. He develops aggregate counting, credit schemes, and the potential method, then applies them to binary counters, doubling array lists, lazily rebuilt search trees with tombstone deletion, and immutable queues built from two stacks.
Key takeaways
- A binary counter performs fewer than 2n bit flips across n increments, so increment is O(1) amortized even though one increment can flip Θ(n) bits.
- A credit scheme is valid only when every expensive operation can be paid for with credits accumulated earlier; the binary-counter scheme allocates a geometric series totaling less than 2 credits per increment.
- Doubling an array makes append O(1) amortized: the linear copying cost at capacity n is covered by credits accumulated across the preceding Θ(n) appends.
- A search tree rebuilt when subtree sizes become substantially unbalanced can maintain O(log n) height while charging occasional linear rebuilds to accumulated subtree imbalance.
- Tombstone deletion postpones tree cleanup until many nodes are marked; rebuilding when roughly half the nodes are deleted lets accumulated deletion credits pay for garbage collection.
- An immutable queue can use two linked-list stacks and reverse the input stack only when the output stack empties, achieving O(1) amortized enqueue and dequeue.
Chapters
- Amortized analysis keeps deterministic worst-case guarantees over sequences of operations, rather than assuming inputs come from a probability distribution.
- Kent Quanrud contrasts amortized analysis with randomized algorithms, which deliberately use coin flips and analyze expected behavior on any fixed input.
- The tradeoff is simpler, practical algorithms paired with more involved analysis of how operation costs add up.
- An n-bit binary counter can take Θ(n) time for one increment when a carry resets many trailing 1 bits.
- The worst case is misleading for repeated increments, since most increments change only a few low-order bits.
- The counter from 0 to n provides a warm-up for proving a sequence-wide running-time bound.
- The least significant bit flips every increment, the second bit every other increment, and bit k every 2^(k-1) increments.
- Across n increments, the total number of flips is bounded by n + n/2 + n/4 + … < 2n.
- The resulting constant amortized time means the full sequence takes O(n), despite individual increments taking Θ(n) in the worst case.
- The aggregate method directly bounds the total cost of a sequence, as with the binary counter's fewer than 2n flips.
- A credit scheme charges operations extra units that are saved to pay for later expensive work.
- The potential method assigns a value to the data structure's state and uses increases or decreases in that value to account for actual cost.
- For each increment, allocate one credit to the least significant bit, one-half credit to the next bit, one-quarter to the third, and so on.
- Each bit receives enough accumulated credit to pay for its next flip, while the total credit allocated per increment is less than 2.
- The key accounting rule is that an operation can spend only credits already saved, never borrow from future operations.
- A potential function maps the current data-structure state to a numerical value, analogous to stored energy that can later be released.
- An operation's amortized cost combines its actual cost with the change in potential.
- Potential increases can pay for later costly work when an operation sharply decreases the stored value.
- Set the binary counter's potential equal to its number of 1 bits.
- An increment that flips t trailing 1s to 0 and one 0 to 1 costs t + 1 actual flips, while potential changes by 1 - t.
- The amortized cost is therefore 2 per increment, giving O(n) total time for n increments.
- Java ArrayList-style storage keeps elements in a contiguous array, allowing constant-time indexed access.
- When the array fills, doubling its capacity requires allocating a larger array and copying the existing elements, an O(n) operation.
- The doubling trick leaves unused capacity for future appends, so the expensive resize is occasional rather than required for every insertion.
- Charge each append a constant amount beyond its immediate work and save the extra credits as elements are added.
- By the time a full array of size n must grow to size 2n, a linear number of elements have accumulated credits to pay for copying.
- Appending remains O(n) in the worst case during a resize, but takes O(1) amortized time over a sequence.
- A binary search tree sends smaller keys left and larger keys right, supporting searches and range queries along root-to-leaf paths.
- Storing each subtree's node count lets a range-count query skip subtrees fully inside the requested interval.
- If keys are inserted in sorted order into an ordinary, unrebalanced tree, it can degenerate into a path with linear height.
- The proposed simple balancing rule tracks subtree sizes and rebuilds a subtree when its children become substantially unbalanced.
- A rebuild lists the already ordered keys and recursively chooses middle elements to form a balanced tree.
- Keeping child sizes within a constant-factor ratio ensures the height stays O(log n), so ordinary search paths remain logarithmic.
- Assign each node a potential based on the absolute difference between its left- and right-subtree sizes, then sum these values across the tree.
- A single insertion changes the potential at O(log n) nodes along its search path, yielding O(log n) potential increase.
- When a highly unbalanced subtree is rebuilt, its large accumulated potential drop helps pay for the linear rebuilding cost.
- Instead of restructuring the tree immediately, deletion marks the target node as a tombstone.
- When a substantial fraction of a tree's nodes, such as half, are marked deleted, rebuild the tree and discard the tombstones.
- Potential for deleted nodes pays for garbage collection, while subtree-imbalance potential continues to account for insertion-triggered rebuilds.
- In functional programming, immutable values cannot be overwritten, which reduces side effects and makes concurrent code easier to reason about.
- A linked list naturally supports an immutable stack: pushing creates a new head node, and popping advances the head pointer.
- When an object changes, unchanged linked structures can be shared rather than copied in full.
- Maintain an input stack for enqueues and an output stack for dequeues; when the output stack is empty, reverse the input stack into it.
- Reversing k elements costs O(k) at that moment, but a potential equal to the input-stack size supplies k units to pay for the transfer.
- Each element is transferred only occasionally, giving O(1) amortized queue operations while retaining immutable data structures.
Transcript excerpt
0:04 Um so today is going to be about lazy data structures. Uh often this is a popular lecture because you're familiar with like half of it coming out of your discrete math class or the data structures class. Um but yeah, so the um the the last leg of our class, we're going to look at two different styles of of average case analysis of algorithms. uh but I want to be very careful here. I'm not talking about average case in the sense of like the input is random or from some statistical distribution anyway. So this is not in the machine learning sense of the word average. We're going to keep track of all of our kind of worst case guarantees. And so the first example, the first of these uh which we'll do today is something called amvertise analysis. You've already seen
0:51 this with the Fibonacci heat. Okay? But we're going to argue that we're going to have data structures that um are kind of non-uniform. They occasionally might spend a long time doing something like garbage collection or something. But if you look backwards, you know, after 100 operations, it always look pretty good on average. Okay? It's going to be very rigorous and stuff and you won't lose any worst case guarantees. Okay? And the other sense of of average we're going to look at on Thursday is randomized algorithms. So these are algorithms that deliberately flip coins. Okay. And and then we'll analyze them as kind of random uh experiments, you know, probabilistic things. Um but again, the input will always be worst case. It's like, oh, no matter the input, on average, this random algorithm will act
1:38 like this or something. Yeah. Um and uh you know, some of they're actually both very very practical. In in both cases,
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Kent Quanrud.