Add screen-reader figure descriptions for English, Japanese, Korean, and Russian (#2043)

* Translate screen-reader figure descriptions into four book languages

* Clarify the spoken exponent in the time-complexity table

* Polish translated figure explanations and spoken math after full-book review
This commit is contained in:
Yudong Jin
2026-11-18 16:23:32 +08:00
committed by GitHub
parent 2c043775ac
commit 53611a0ae9
881 changed files with 100307 additions and 27 deletions

View File

@@ -0,0 +1,56 @@
{
"schema_version": 2,
"title": "Array elements, indices, and memory addresses",
"summary": "An array locates elements using 0-based indices, storing all elements contiguously in memory in equal-sized slots.",
"context": [],
"description": [
"The left side lists the array, indices, and memory addresses; in the second row of the grid on the right, 5 contiguous green cells represent the memory allocated to the array, while the remaining light gray cells represent free memory."
],
"result": "An index is an element's ordinal position in the array, the element value is the data stored at that position, and the memory address is the starting number of its storage unit; the three are distinct concepts.",
"frames": [
{
"id": "source-46",
"book_path": "chapter_array_and_linkedlist/array.assets/array_definition.png",
"title": "Array elements, indices, and memory addresses",
"explanation": "In this example, each element occupies 4 bytes, so the starting addresses of adjacent elements always differ by 4. The leading 0 in an address only pads the width and does not indicate octal notation."
}
],
"tables": [
{
"caption": "Positions and memory addresses of the five elements",
"headers": [
"Index",
"Element value",
"Starting memory address"
],
"rows": [
[
"0",
"1",
"00"
],
[
"1",
"3",
"04"
],
[
"2",
"2",
"08"
],
[
"3",
"5",
"12"
],
[
"4",
"4",
"16"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,125 @@
{
"schema_version": 2,
"title": "Inserting an element into an array",
"summary": "Insert element 3 at index 1: first copy existing elements one position to the right starting from the end, then write the new element.",
"context": [
"Array nums has 5 slots at indices 0 through 4. Its initial storage is [1, 2, 5, 4, 0], where only the first 4 elements [1, 2, 5, 4] are valid and the trailing 0 at index 4 is an unused placeholder. The goal is to insert 3 at index 1 while preserving the relative order of the existing valid elements."
],
"description": [],
"result": "After insertion, all 5 slots hold valid elements; the caller updates the valid length to 5 accordingly, whereas the sample insert function itself only assigns slot values. When the text later notes that the last element of a fixed-length array is \"lost\", in this example only the placeholder 0 in the last slot is overwritten, so none of the four original valid elements are lost. Had all 5 slots originally held valid elements, overwriting would lose the final valid element, requiring array expansion beforehand or rejecting the insertion.",
"frames": [
{
"id": "source-48",
"book_path": "chapter_array_and_linkedlist/array.assets/array_insert_element.png",
"title": "Inserting an element into an array",
"explanation": "Copying backward from the end toward the insertion point ensures that every element about to be overwritten and still needed has already been copied to the adjacent slot on its right. Copying does not clear the source slot, so duplicate values appear in intermediate states. Inserting into the middle of an array shifts O(n) elements on average."
}
],
"animations": {
"flow-array-insert": {
"kind": "prose",
"prose": {
"title": "Inserting an element into an array",
"summary": "Insert element 3 at index 1: first copy existing elements one position to the right starting from the end, then write the new element.",
"context": [
"Array nums has 5 slots at indices 0 through 4. Its initial storage is [1, 2, 5, 4, 0], where only the first 4 elements [1, 2, 5, 4] are valid and the trailing 0 at index 4 is an unused placeholder. The goal is to insert 3 at index 1 while preserving the relative order of the existing valid elements."
],
"description": [],
"result": "After insertion, all 5 slots hold valid elements; the caller updates the valid length to 5 accordingly, whereas the sample insert function itself only assigns slot values. When the text later notes that the last element of a fixed-length array is \"lost\", in this example only the placeholder 0 in the last slot is overwritten, so none of the four original valid elements are lost. Had all 5 slots originally held valid elements, overwriting would lose the final valid element, requiring array expansion beforehand or rejecting the insertion.",
"steps": [
{
"id": "step-1",
"title": "Prepare for insertion",
"explanation": "Current storage is [1, 2, 5, 4, 0] with valid length 4, and the trailing 0 is a placeholder. Index 1 holds the valid element 2, so writing 3 directly would overwrite and lose it; the elements at indices 1 through 3 must first be copied to the right.",
"key_state": "Ready to insert 3 at index 1; current storage is [1, 2, 5, 4, 0], the valid sequence is [1, 2, 5, 4], and the trailing 0 is a placeholder.",
"announcement": "Show initial array [1, 2, 5, 4, 0] and prepare to shift existing elements right before inserting 3 at index 1."
},
{
"id": "step-2",
"title": "Copy the trailing 4",
"explanation": "Execute nums[4] = nums[3] to copy 4 to index 4, overwriting the placeholder 0. Current storage is [1, 2, 5, 4, 4]; since the 4 from index 3 is now preserved, index 3 can safely be overwritten in the next step. Because 3 has not been written yet, the valid length remains 4.",
"key_state": "Executed nums[4] = nums[3] to copy 4; current storage is [1, 2, 5, 4, 4].",
"announcement": "Execute nums[4] = nums[3] to copy 4 from index 3 to index 4, overwriting the placeholder 0."
},
{
"id": "step-3",
"title": "Copy 5",
"explanation": "Execute nums[3] = nums[2] to copy 5 to index 3, making current storage [1, 2, 5, 5, 4]. The original 4 is already saved in the last slot and will not be lost; next, 2 must still be copied before writing 3. The valid length remains 4.",
"key_state": "Executed nums[3] = nums[2] to copy 5; current storage is [1, 2, 5, 5, 4], with only 4 and 5 copied so far and 3 not yet written.",
"announcement": "Execute nums[3] = nums[2] to copy 5 from index 2 to index 3."
},
{
"id": "step-4",
"title": "Copy 2",
"explanation": "Execute nums[2] = nums[1] to copy 2 to index 2, making current storage [1, 2, 2, 5, 4]. The original elements 2, 5, and 4 have now shifted right; index 1 still holds 2, which can now be safely overwritten. Because 3 has not been written yet, the valid length remains 4.",
"key_state": "Executed nums[2] = nums[1] to copy 2; rightward shifting is complete, current storage is [1, 2, 2, 5, 4], and 3 is ready to be written.",
"announcement": "Execute nums[2] = nums[1] to copy 2 from index 1 to index 2; index 1 can now be safely overwritten."
},
{
"id": "step-5",
"title": "Write 3",
"explanation": "Execute nums[1] = 3, making current storage [1, 3, 2, 5, 4]. The new element is written and insertion is complete; the number of valid elements increases from 4 to 5, and the caller updates the valid length.",
"key_state": "Executed nums[1] = 3, giving final storage [1, 3, 2, 5, 4]; the caller updates the valid length to 5.",
"announcement": "Write 3 at index 1 to complete insertion, giving array [1, 3, 2, 5, 4]; the caller updates the valid length to 5."
}
]
}
}
},
"tables": [
{
"caption": "Five slots after each assignment",
"headers": [
"Operation",
"Index 0",
"Index 1",
"Index 2",
"Index 3",
"Index 4"
],
"rows": [
[
"Initial state",
"1",
"2",
"5",
"4",
"0"
],
[
"nums[4] = nums[3]",
"1",
"2",
"5",
"4",
"4"
],
[
"nums[3] = nums[2]",
"1",
"2",
"5",
"5",
"4"
],
[
"nums[2] = nums[1]",
"1",
"2",
"2",
"5",
"4"
],
[
"nums[1] = 3",
"1",
"3",
"2",
"5",
"4"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,56 @@
{
"schema_version": 2,
"title": "Calculating an array element's memory address",
"summary": "Compute an element's location directly from the starting address, fixed element size, and index.",
"context": [],
"description": [
"The upper part arranges the array, indices, and memory addresses with the column at index 3 highlighted; the lower part gives the address formula and a worked substitution. Each element occupies 4 bytes; the upper address row uses two-digit notation (such as 00 and 12), while the formula below uses three-digit notation (000 and 012). Leading zeros are purely for alignment, and all numbers are decimal."
],
"result": "With contiguous storage and equal-sized elements, a single multiplication and addition gives the address, supporting O(1) random access.",
"frames": [
{
"id": "source-47",
"book_path": "chapter_array_and_linkedlist/array.assets/array_memory_location_calculation.png",
"title": "Calculating an array element's memory address",
"explanation": "Element address = address of the first element + element size × index. Indexing starts at 0, so index 3 is the 4th element, with value 5; it is 3 elements past the first element, giving a byte offset of 4 × 3 = 12 and an address of 000 + 4 × 3 = 012. This locates the element by index rather than searching for an element whose value is 3."
}
],
"tables": [
{
"caption": "Indices, values, and addresses shown in the figure",
"headers": [
"Index",
"Element value",
"Memory address"
],
"rows": [
[
"0",
"1",
"00"
],
[
"1",
"3",
"04"
],
[
"2",
"2",
"08"
],
[
"3",
"5",
"12"
],
[
"4",
"4",
"16"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,95 @@
{
"schema_version": 2,
"title": "Removing an array element by shifting left",
"summary": "Overwrite the removed position to preserve the order of the remaining elements while distinguishing valid length from total slot count.",
"context": [
"Array nums has 5 slots, initialized to [1, 3, 2, 5, 4] with valid length 5 and 0-based indices. The goal is to remove 3 at index 1 while preserving the order of the remaining elements."
],
"description": [],
"result": "After three copies, the caller updates the valid length from 5 to 4, leaving only [1, 2, 5, 4] at indices 0 through 3 valid; the 4 in the final slot is an unused leftover and need not be zeroed out. The sample remove function only overwrites slots without automatically shortening a Python list; removing an element from the middle takes O(n) time on average.",
"frames": [
{
"id": "source-49",
"book_path": "chapter_array_and_linkedlist/array.assets/array_remove_element.png",
"title": "Removing an array element by shifting left",
"explanation": "Reading adjacent elements sequentially to the right of the removed position and overwriting one slot to the left ensures that every source value is read before it is overwritten. Copying modifies only the destination slot without clearing the source slot, so adjacent duplicate values appear along the way."
}
],
"animations": {
"flow-array-remove": {
"kind": "prose",
"prose": {
"title": "Removing an array element by shifting left",
"summary": "Overwrite the removed position to preserve the order of the remaining elements while distinguishing valid length from total slot count.",
"context": [
"Array nums has 5 slots, initialized to [1, 3, 2, 5, 4] with valid length 5 and 0-based indices. The goal is to remove 3 at index 1 while preserving the order of the remaining elements."
],
"description": [],
"result": "After three copies, the caller updates the valid length from 5 to 4, leaving only [1, 2, 5, 4] at indices 0 through 3 valid; the 4 in the final slot is an unused leftover and need not be zeroed out. The sample remove function only overwrites slots without automatically shortening a Python list; removing an element from the middle takes O(n) time on average.",
"steps": [
{
"id": "step-1",
"title": "Mark element 3 at index 1 for deletion",
"explanation": "Current storage is [1, 3, 2, 5, 4] with valid length 5. Element 3 at index 1 is marked as the element to delete; 2, 5, and 4 to its right will be copied left one by one, after which the caller updates the valid length.",
"key_state": "Initial valid sequence [1, 3, 2, 5, 4], ready to delete 3 at index 1.",
"announcement": "Show initial array [1, 3, 2, 5, 4] and mark element 3 at index 1 for deletion."
},
{
"id": "step-2",
"title": "Copy 2 from index 2 to index 1",
"explanation": "The 1st copy executes nums[1] = nums[2], overwriting the old value 3 with 2 so current storage is [1, 2, 2, 5, 4]. Index 2 still holds 2; next, nums[2] = nums[3] and nums[3] = nums[4] must run before updating the valid length, which is still recorded as 5.",
"key_state": "Executed nums[1] = nums[2]; storage becomes [1, 2, 2, 5, 4].",
"announcement": "Copy 2 from index 2 to index 1, overwriting the original value 3."
},
{
"id": "step-3",
"title": "Copy 5 from index 3 to index 2",
"explanation": "The 2nd copy executes nums[2] = nums[3], overwriting the old value 2 at index 2 with 5 so current storage is [1, 2, 5, 5, 4]. Index 3 still holds 5; next, nums[3] = nums[4] must run before changing the valid length to 4, which is still recorded as 5.",
"key_state": "Executed nums[2] = nums[3]; storage becomes [1, 2, 5, 5, 4].",
"announcement": "Copy 5 from index 3 to index 2."
},
{
"id": "step-4",
"title": "Copy the final 4; caller updates valid length",
"explanation": "The 3rd copy executes nums[3] = nums[4], overwriting the old value 5 at index 3 with 4 so the five slots hold [1, 2, 5, 4, 4]. The caller updates the valid length to 4, leaving only the first four entries [1, 2, 5, 4] valid; the leftover 4 at index 4 is unused and need not be zeroed out.",
"key_state": "Executed nums[3] = nums[4], leaving the five slots as [1, 2, 5, 4, 4]; the caller updates the valid length to 4 so only the first four entries are valid and the trailing 4 is an unused leftover.",
"announcement": "Copy 4 from index 4 to index 3; the caller updates the valid length to 4, giving valid sequence [1, 2, 5, 4] while leaving 4 in the last slot as an unused leftover."
}
]
}
}
},
"tables": [
{
"caption": "Complete slot storage during leftward shifting",
"headers": [
"State or assignment",
"Stored contents",
"Valid length or meaning"
],
"rows": [
[
"Initial",
"[1,3,2,5,4]",
"5; 3 at index 1 is to be deleted"
],
[
"1st copy: nums[1]=nums[2]",
"[1,2,2,5,4]",
"In progress, recorded length 5"
],
[
"2nd copy: nums[2]=nums[3]",
"[1,2,5,5,4]",
"In progress, recorded length 5"
],
[
"3rd copy: nums[3]=nums[4]; caller updates valid length to 4",
"[1,2,5,4,4]",
"4; only the first 4 entries are valid, with trailing 4 left over"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,45 @@
{
"schema_version": 2,
"title": "Three common types of linked lists",
"summary": "Compare the link structures of singly, circular, and doubly linked lists using the same nodes 1, 3, 2, 5, and 4.",
"context": [
"All three rows use five nodes arranged in the order 1, 3, 2, 5, 4, comparing the three connection patterns from top to bottom."
],
"description": [],
"frames": [
{
"id": "source-53",
"book_path": "chapter_array_and_linkedlist/linked_list.assets/linkedlist_common_types.png",
"title": "Three common types of linked lists",
"explanation": "A singly linked list can only be traversed forward along successor references; in a circular linked list, any node can serve as the head; a doubly linked list can be traversed in both directions via next or prev, at the cost of storing an extra predecessor reference."
}
],
"tables": [
{
"caption": "References and boundaries of the three linked list types",
"headers": [
"Type and position",
"Between adjacent nodes",
"Head and tail boundaries"
],
"row_header": 0,
"rows": [
[
"Singly linked list, top",
"Rightward next: 1 → 3 → 2 → 5 → 4",
"Tail node 4 has next pointing to None"
],
[
"Circular linked list, middle",
"Rightward next: 1 → 3 → 2 → 5 → 4",
"Tail node 4 routes back beneath the row to node 1, forming a closed loop"
],
[
"Doubly linked list, bottom",
"Node order is 1, 3, 2, 5, 4; between every adjacent pair, rightward next points to the successor and leftward prev points to the predecessor",
"Node 1 has prev pointing to None on the left, and node 4 has next pointing to None on the right"
]
]
}
]
}

View File

@@ -0,0 +1,15 @@
{
"schema_version": 2,
"title": "Linked list nodes and links",
"summary": "The figure consists of a logical view and a memory grid showing the same linked list. In the grid, each node occupies two adjacent cells storing its value and its successor reference next (pointer); the remaining light-colored cells represent free memory, with cell sizes shown schematically.",
"context": [],
"description": [],
"frames": [
{
"id": "source-50",
"book_path": "chapter_array_and_linkedlist/linked_list.assets/linkedlist_definition.png",
"title": "Linked list nodes and links",
"explanation": "The linked list has 5 nodes connected along next references as 1 → 3 → 2 → 5 → 4 → None. The head node is 1, the tail node is 4, and None indicates that there is no next node. In the memory grid, nodes 2 and 5 sit lower down while the tail node 4 sits near the top: node 5's next still points to 4, showing that logical order is determined by references rather than physical location."
}
]
}

View File

@@ -0,0 +1,87 @@
{
"schema_version": 2,
"title": "Inserting a node into a linked list",
"summary": "To insert a new node P between adjacent nodes n0 and n1, update only two references in order: P.next and then n0.next.",
"context": [
"Predecessor node n0 has value 1 and successor node n1 has value 3; initially n0.next points to n1, and the ellipsis to the right of n1 represents the rest of the list. Node P to be inserted has value 0 and is not yet linked into the list. Here next denotes a node's successor pointer (reference)."
],
"description": [],
"result": "All node values and all links after n1 remain unchanged. Given the predecessor n0, updating the two references takes O(1) time without shifting any subsequent nodes.",
"frames": [
{
"id": "source-51",
"book_path": "chapter_array_and_linkedlist/linked_list.assets/linkedlist_insert_node.png",
"title": "Inserting a node into a linked list",
"explanation": "Linking the new node to the original successor before pointing the predecessor to the new node avoids losing the rest of the list. The code first saves n0.next in n1 and then performs the two assignments in the order shown. Traversal from n0 passes through P only after the second assignment completes."
}
],
"animations": {
"flow-linked-insert": {
"kind": "prose",
"prose": {
"title": "Inserting a node into a linked list",
"summary": "To insert a new node P between adjacent nodes n0 and n1, update only two references in order: P.next and then n0.next.",
"context": [
"Predecessor node n0 has value 1 and successor node n1 has value 3; initially n0.next points to n1, and the ellipsis to the right of n1 represents the rest of the list. Node P to be inserted has value 0 and is not yet linked into the list. Here next denotes a node's successor pointer (reference)."
],
"description": [],
"result": "All node values and all links after n1 remain unchanged. Given the predecessor n0, updating the two references takes O(1) time without shifting any subsequent nodes.",
"steps": [
{
"id": "step-1",
"title": "Initial links",
"explanation": "The initial chain is n0 (1) → n1 (3) → …, with n0.next pointing to n1. Node P (0) to be inserted stands separate outside the list, and the figure does not draw an initial target for P.next.",
"key_state": "Initial state: n0.next = n1, while node P (value 0) stands separate and unlinked.",
"announcement": "Show initial linked list n0 (1) → n1 (3) and node P (0) to be inserted."
},
{
"id": "step-2",
"title": "Link P to its successor",
"explanation": "Execute P.next = n1. The next pointers of n0 (value 1) and P (value 0) now both point to n1 (value 3), while links after n1 remain unchanged. Starting from n0 still leads directly to n1 without passing through P yet.",
"key_state": "Executed P.next = n1 while n0.next still points to n1 (both point to n1); traversal from n0 does not yet pass through P.",
"announcement": "Execute P.next = n1 so new node P points to successor n1 first."
},
{
"id": "step-3",
"title": "Link P into the list",
"explanation": "Execute n0.next = P while keeping P.next = n1. The chain becomes n0 (1) → P (0) → n1 (3) → …, so starting from n0 now visits P before continuing to the rest of the list, completing the insertion.",
"key_state": "Executed n0.next = P with P.next = n1; the final list is n0 (1) → P (0) → n1 (3) → ….",
"announcement": "Execute n0.next = P to complete insertion; the list becomes n0 (1) → P (0) → n1 (3) → subsequent nodes."
}
]
}
}
},
"tables": [
{
"caption": "Links during node insertion",
"headers": [
"Stage",
"n0.next",
"P.next",
"Nodes visited starting from n0"
],
"rows": [
[
"Initial",
"n1",
"Target not drawn",
"n0 → n1 → …"
],
[
"Link P to successor",
"n1",
"n1",
"n0 → n1 → …"
],
[
"Insertion complete",
"P",
"n1",
"n0 → P → n1 → …"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,52 @@
{
"schema_version": 2,
"title": "Removing a linked list node",
"summary": "Redirect the predecessor node's successor reference to bypass the node being removed.",
"context": [
"The local sublist is n0 (1) → P (0) → n1 (3) → …. Given predecessor n0, the goal is to delete node P; n0 is not necessarily the head of the entire list."
],
"description": [
"The figure has upper and lower panels; after deletion, P and its arrow to n1 turn dashed and remain visible for comparison, while memory deallocation is not depicted."
],
"result": "Given predecessor node n0, redirecting a single reference takes O(1) time and no other nodes need to move; the time to locate the predecessor is not included in this step.",
"frames": [
{
"id": "source-52",
"book_path": "chapter_array_and_linkedlist/linked_list.assets/linkedlist_remove_node.png",
"title": "Removing a linked list node",
"explanation": "After executing n0.next = n1, the main chain becomes n0 (1) → n1 (3) → …. Although P.next still points to n1, traversing forward from the list head through n0 can no longer reach P, so logical deletion is complete."
}
],
"animations": {
"linkedlist-remove": {
"kind": "prose",
"prose": {
"title": "Removing a linked list node",
"summary": "Redirect the predecessor node's successor reference to bypass the node being removed.",
"context": [
"The local sublist is n0 (1) → P (0) → n1 (3) → …. Given predecessor n0, the goal is to delete node P; n0 is not necessarily the head of the entire list."
],
"description": [
"The figure has upper and lower panels; after deletion, P and its arrow to n1 turn dashed and remain visible for comparison, while memory deallocation is not depicted."
],
"result": "Given predecessor node n0, redirecting a single reference takes O(1) time and no other nodes need to move; the time to locate the predecessor is not included in this step.",
"steps": [
{
"id": "step-1",
"title": "Before deletion: n0 → P → n1",
"explanation": "Current links are n0 (1) → P (0) → n1 (3) → …. Here n0.next points to P and P.next points to n1, so starting from n0 must pass through P to reach n1. Next, n0.next will be redirected.",
"key_state": "Before deletion, n0 → P → n1, and P is reachable from n0.",
"announcement": "Before deletion: n0, P, and n1 are linked in sequence, ready to bypass node P."
},
{
"id": "step-2",
"title": "Redirect reference: n0.next = n1",
"explanation": "Execute n0.next = n1, changing the main chain to n0 (1) → n1 (3) → …. Node P (0)'s next still points to n1, but forward traversal from the list head past n0 can no longer reach P, completing logical deletion.",
"key_state": "n0.next = n1, so the main chain becomes n0 → n1; P is unreachable though it still points to n1.",
"announcement": "Set n0.next directly to n1 so node P becomes unreachable from the list, completing deletion."
}
]
}
}
}
}

View File

@@ -0,0 +1,18 @@
{
"schema_version": 2,
"title": "Data flow between disk, memory, and cache",
"summary": "The processor, cache, memory, and disk work together through bidirectional data flows.",
"context": [],
"description": [
"From left to right are CPU, Memory, and Disk. Inside the green CPU box, Processor is on the left and Cache is on the right. Between each of the three adjacent pairs—Processor and Cache, Cache and Memory, and Memory and Disk—sit two horizontal arrows stacked vertically: the upper arrow points right and the lower arrow points left.",
"Above the boxes, two bent arrows bypass Cache, one pointing from Processor to Memory and the other from Memory to Processor. Together these connections represent bidirectional read and write paths."
],
"frames": [
{
"id": "source-55",
"book_path": "chapter_array_and_linkedlist/ram_and_cache.assets/computer_storage_devices.png",
"title": "Data flow between disk, memory, and cache",
"explanation": "As the chapter explains, the disk stores data long term. Data needed at runtime is loaded into memory. The CPU cache holds frequently accessed data and instructions so the processor makes fewer trips to slower memory."
}
]
}

View File

@@ -0,0 +1,55 @@
{
"schema_version": 2,
"title": "Pyramid hierarchy of computer storage",
"summary": "The storage pyramid compares speed, capacity, cost per unit capacity, and persistence across storage levels.",
"context": [
"The pyramid widens from top to bottom across five levels. The top three levels sit inside a green box labeled CPU and are grouped on the left as \"Cache\"; the fourth level is labeled \"Memory\", and the fifth level is labeled \"Disk\"."
],
"description": [],
"frames": [
{
"id": "source-54",
"book_path": "chapter_array_and_linkedlist/ram_and_cache.assets/storage_pyramid.png",
"title": "Pyramid hierarchy of computer storage",
"explanation": "On the right, the upward arrow is labeled \"Speed, Cost\": higher levels provide faster access at higher cost per unit capacity. The downward arrow is labeled \"Capacity, Persistence\": lower levels offer larger capacity, and HDD/SSD at the bottom retains data long term without power. Cache and memory are volatile storage and lose data when power is removed."
}
],
"tables": [
{
"caption": "Five storage levels from top to bottom",
"headers": [
"Level",
"Label in figure",
"Category"
],
"row_header": 0,
"rows": [
[
"1, top",
"L1 Cache",
"Cache inside CPU"
],
[
"2",
"L2 Cache",
"Cache inside CPU"
],
[
"3",
"L3 Cache",
"Cache inside CPU"
],
[
"4",
"RAM",
"Memory"
],
[
"5, bottom",
"HDD/SSD",
"Disk"
]
]
}
]
}

View File

@@ -0,0 +1,43 @@
{
"schema_version": 2,
"title": "Whether to keep searching after recording a solution",
"summary": "When valid solutions may still exist among a target node's descendants, returning immediately after recording a solution misses deeper solutions; that early return must be removed so the search continues.",
"context": [
"The task is to find all paths starting at the root, ending at a node with value 7, and containing no node with value 3. The binary tree shown has 8 nodes: root 1 has left and right children 7 and 3; the left (shallower) 7 has left and right children 4 and 5, with a deeper left child 7 beneath 4; and 3 has left and right children 6 and the right 7. Compared with the seven-node input in the earlier example and accompanying Python code, this figure adds the deeper left child 7 beneath 4; on that seven-node tree, removing the return after recording a solution would not add any solutions.",
"What is compared here is whether to execute return immediately after recording a solution to end the current recursive branch. Pruning that stops descending at node 3 and normal backtracking after visiting a node's children remain unchanged in both approaches; the template code implements that pruning by rejecting choices with value 3."
],
"description": [
"The left and right panels respectively keep and remove the early return after recording a solution. The table below compares which nodes each search visits and resulting paths; in the right branch, both panels stop descending upon reaching the red node 3, skipping 6 and the right 7."
],
"frames": [
{
"id": "source-341",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/backtrack_remove_return_or_not.png",
"title": "Whether to keep searching after recording a solution",
"explanation": "Only by continuing deeper after recording the shallower 7 can the right panel discover the deeper 7 among its descendants; ending the current branch early misses that solution."
}
],
"tables": [
{
"caption": "Handling after recording a solution and resulting paths",
"headers": [
"Approach",
"Nodes visited next",
"Paths found"
],
"rows": [
[
"Left panel: keep early return",
"Stops at the shallower 7 without visiting its descendants 4, 5, and the deeper 7",
"[1, 7]"
],
[
"Right panel: remove early return",
"Continues after recording the shallower 7 to visit 4, the deeper 7, and 5",
"[1, 7]; [1, 7, 4, 7]"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,21 @@
{
"schema_version": 2,
"title": "Pruning with the constraint that paths exclude 3",
"summary": "When searching for root-to-7 paths that do not contain 3, return early at node 3 to prune its subtree, skipping node 6 and the right 7.",
"context": [
"The binary tree has seven nodes: root 1 has left and right children 7 and 3; the left node 7 has left and right children 4 and 5; node 3 has left and right children 6 and another 7; nodes 4, 5, 6, and the right 7 are all leaf nodes.",
"The problem asks for paths from the root to all nodes with value 7 such that no path contains a node with value 3. Any path extending downward past node 3 necessarily violates this constraint."
],
"description": [
"The left subtree contains no 3, so preorder traversal records the valid path [1, 7] upon visiting the left node 7 and continues checking its children 4 and 5.",
"Reaching the root's right child 3 triggers the constraint, so the algorithm returns immediately before appending 3 to path and does not recurse into its children 6 and the right 7. The figure marks node 3 in red and uses a scissors icon with a faded subtree to show that this search branch is skipped; the tree nodes themselves are not deleted from the data structure."
],
"frames": [
{
"id": "source-340",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_constrained_paths.png",
"title": "Return early at node 3 to prune the invalid search branch",
"explanation": "The only path satisfying the constraint is [1, 7]. Although the right leaf node 7 equals the target value 7, the path [1, 3, 7] from the root to it passes through the forbidden node 3 and is therefore ruled out during pruning."
}
]
}

View File

@@ -0,0 +1,21 @@
{
"schema_version": 2,
"title": "Finding and recording all nodes with value 7 during preorder traversal",
"summary": "Traverse the seven nodes in root-left-right preorder, matching and recording the root's left child 7 followed by node 3's right child 7.",
"context": [
"The binary tree has seven nodes: root 1 has left and right children 7 and 3; the left node 7 has left and right children 4 and 5; node 3 has left and right children 6 and another 7; nodes 4, 5, 6, and the right 7 are all leaf nodes.",
"The problem requires finding and recording every node in the tree with value 7 rather than stopping at the first match. The two cyan-highlighted 7s lie in different branches and represent two distinct node objects."
],
"description": [
"Green dashed arrows trace the depth-first traversal contour around the binary tree, while the orange dot to the left of each node marks the preorder visit point: check the node's value immediately upon entering the node, then recurse into its left subtree and right subtree in turn.",
"The full-tree preorder visit sequence is [1, 7, 4, 5, 3, 6, 7]. Whenever a node with value 7 is reached, it is appended to the result list and traversal continues through the remaining branches; thus after matching the left node 7, the search still visits its children 4 and 5."
],
"frames": [
{
"id": "source-339",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_nodes.png",
"title": "Check and record target nodes at the preorder visit point",
"explanation": "The code records two node objects in res, in order of discovery: the root's left child 7 and node 3's right child 7; displayed by node value, this is [7, 7], corresponding to two nodes at different positions in the tree."
}
]
}

View File

@@ -0,0 +1,206 @@
{
"schema_version": 2,
"title": "Trying choices and backtracking: saving paths to 7",
"summary": "Append each node to path on entry and pop it on exit; copy and save path on each of the two matches with 7, leaving path empty when the search ends.",
"context": [
"The parent-child relationships of the fixed tree are shown in the table below. The left 7 is the left child of root 1, and the right 7 is the right child of node 3.",
"Traverse the entire tree in \"root → left → right\" preorder to find the paths from root node 1 to every node with value 7.",
"The state list path maintains the active path from the root to the current node in real time, and the result list res stores a copy of path each time a 7 is matched. The figure abbreviates path and res using node values, whereas the accompanying code stores node objects and list copies list(path); the left and right nodes with value 7 are distinct objects."
],
"description": [
"Each forward \"trial\" entering a node appends it to the end of path; if the current node has value 7, a copy of path is appended to res; before \"backtracking\" out of a node, it is popped from the end of path to restore the path from before entering that node."
],
"result": "Because res stores independent list copies of path taken at each match, popping during backtracking modifies only the active path without altering previously saved solutions.",
"frames": [
{
"id": "source-342",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step1.png",
"title": "Enter root 1",
"explanation": "Start at root node 1 and append 1 to path. Node value 1 is not the target 7, so path = [1] and res = []; both subtrees remain to be explored, and the search next enters the left 7.",
"key_state": "Entered root 1; path = [1], res = [].",
"announcement": "Enter root node 1 and append 1 to path."
},
{
"id": "source-343",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step2.png",
"title": "Match left 7 and save path",
"explanation": "Enter the left 7 from root 1, append 7, and match the target, saving a copy of the current path to res. Now path = [1, 7] and res = [[1, 7]]; continue exploring the left 7's children 4 and 5.",
"key_state": "Matched left 7; path = [1, 7], and after copying and saving, res = [[1, 7]].",
"announcement": "Visit the left node 7 and save path copy [1, 7] to res."
},
{
"id": "source-344",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step3.png",
"title": "Enter node 4",
"explanation": "Enter the left leaf node 4 of the left 7 and append 4 to path; it is not the target 7. Now path = [1, 7, 4] and res = [[1, 7]]; node 5 and the root's right subtree remain to be explored.",
"key_state": "Entered leaf node 4; path = [1, 7, 4], res = [[1, 7]].",
"announcement": "Enter left leaf node 4, updating path to [1, 7, 4]."
},
{
"id": "source-345",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step4.png",
"title": "Exit 4 and return to left 7",
"explanation": "Both empty subtrees of leaf node 4 have returned, so pop 4 from path and return to its parent, the left 7. Now path = [1, 7] and res = [[1, 7]]; node 4 is finished, and the right child 5 is explored next.",
"key_state": "Popped 4 and backtracked to left 7; path is restored to [1, 7], res = [[1, 7]].",
"announcement": "Backtrack from leaf node 4 and pop 4, restoring path to [1, 7]."
},
{
"id": "source-346",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step5.png",
"title": "Enter node 5",
"explanation": "Enter the right leaf node 5 of the left 7 and append 5 to path; the previously popped sibling node 4 does not linger. Now path = [1, 7, 5] and res = [[1, 7]]; all nodes in the left subtree have been visited, and the root's right subtree remains to be explored.",
"key_state": "Entered leaf node 5; path = [1, 7, 5], res = [[1, 7]].",
"announcement": "Enter right leaf node 5, updating path to [1, 7, 5]."
},
{
"id": "source-347",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step6.png",
"title": "Exit 5 and left 7",
"explanation": "After finishing node 5, first pop 5 to return to the left 7; since both of its subtrees are now complete, pop the left 7 as well to return to root 1. This frame combines those two backtracking steps. Now path = [1] and res = [[1, 7]]; next explore the root's right child 3.",
"key_state": "Popped 5 and left 7 in succession to return to root 1; path is restored to [1], while res remains [[1, 7]].",
"announcement": "Exit node 5 and left 7 in succession, restoring path to [1]."
},
{
"id": "source-348",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step7.png",
"title": "Enter node 3",
"explanation": "Enter the right child 3 of root 1 and append 3 to path; it is not the target 7. Now path = [1, 3] and res = [[1, 7]]; continue exploring node 3's left leaf 6 and right leaf 7.",
"key_state": "Entered right child 3; path = [1, 3], res = [[1, 7]].",
"announcement": "Enter the root's right child 3, updating path to [1, 3]."
},
{
"id": "source-349",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step8.png",
"title": "Enter node 6",
"explanation": "Enter the left leaf node 6 of node 3 and append 6 to path; it is not the target 7. Now path = [1, 3, 6] and res = [[1, 7]]; across the whole tree, only node 3's right child 7 remains unvisited.",
"key_state": "Entered leaf node 6; path = [1, 3, 6], res = [[1, 7]].",
"announcement": "Enter left leaf node 6, updating path to [1, 3, 6]."
},
{
"id": "source-350",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step9.png",
"title": "Exit 6 and return to 3",
"explanation": "Leaf node 6 is finished, so pop 6 from path and return to parent node 3. Now path = [1, 3] and res = [[1, 7]]; node 6 is complete, and the right 7 is explored next.",
"key_state": "Popped 6 and backtracked to node 3; path is restored to [1, 3], res = [[1, 7]].",
"announcement": "Backtrack from leaf node 6 and pop 6, restoring path to [1, 3]."
},
{
"id": "source-351",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step10.png",
"title": "Match right 7 and save path",
"explanation": "Enter the right leaf node 7 of node 3, append 7 to match the second target node, and save a copy of path to res. Now path = [1, 3, 7] and res = [[1, 7], [1, 3, 7]]; all nodes have been visited, leaving only the final cleanup backtracking.",
"key_state": "Matched right 7; path = [1, 3, 7], and after copying and saving, res = [[1, 7], [1, 3, 7]].",
"announcement": "Visit the right node 7 and save the second path copy [1, 3, 7] to res."
},
{
"id": "source-352",
"book_path": "chapter_backtracking/backtracking_algorithm.assets/preorder_find_paths_step11.png",
"title": "Exit right 7, 3, and root 1",
"explanation": "After finishing the right 7, pop the right 7, parent node 3, and root 1 from path in order. This frame combines the three final backtracking steps, ending the search with path = [] and res = [[1, 7], [1, 3, 7]]; the saved copies remain intact.",
"key_state": "Popped right 7, 3, and root 1 in order to complete the three final backtracking steps; path = [], res = [[1, 7], [1, 3, 7]].",
"announcement": "Exit right 7, node 3, and root 1 in order; path is now empty and the search is complete."
}
],
"animations": {
"preorder-find-paths": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-342"
},
{
"id": "step-2",
"frame_id": "source-343"
},
{
"id": "step-3",
"frame_id": "source-344"
},
{
"id": "step-4",
"frame_id": "source-345"
},
{
"id": "step-5",
"frame_id": "source-346"
},
{
"id": "step-6",
"frame_id": "source-347"
},
{
"id": "step-7",
"frame_id": "source-348"
},
{
"id": "step-8",
"frame_id": "source-349"
},
{
"id": "step-9",
"frame_id": "source-350"
},
{
"id": "step-10",
"frame_id": "source-351"
},
{
"id": "step-11",
"frame_id": "source-352"
}
]
}
},
"tables": [
{
"caption": "Fixed binary tree: distinguishing the two nodes with value 7",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"Root 1",
"Left 7",
"3"
],
[
"Left 7",
"4",
"5"
],
[
"3",
"6",
"Right 7"
],
[
"4",
"None",
"None"
],
[
"5",
"None",
"None"
],
[
"6",
"None",
"None"
],
[
"Right 7",
"None",
"None"
]
],
"row_header": 0
}
],
"input_tables": [
0
]
}

View File

@@ -0,0 +1,106 @@
{
"schema_version": 2,
"title": "Tracking queen constraints with three Boolean arrays",
"summary": "Use the column array cols and diagonal arrays diags1 and diags2, mapped from zero-based row and column coordinates, to record and check queen occupancy.",
"context": [
"This figure matches the code implementation: on a 4×4 board (n = 4), row index row increases top to bottom and column index col increases left to right, both starting at 0 (zero-based indexing). The queen shown sits at zero-based coordinates (1, 1) (the second row and second column); in the Boolean arrays, T denotes occupied and F denotes free."
],
"description": [
"Squares on the same main diagonal share the same row − col, and squares on the same antidiagonal share the same row + col. A candidate square (row, col) looks up the three arrays at col, row − col + n − 1, and row + col; a queen can be placed there only if all three entries are F. When n = 4, row − col ranges from −3 to 3, and adding 3 maps it to nonnegative indices 0 through 6.",
"Placing a queen sets the three corresponding entries to T, and backtracking restores them to F. The two tables below list the indexing rules and the complete values of the three arrays shown in the figure."
],
"frames": [
{
"id": "source-366",
"book_path": "chapter_backtracking/n_queens_problem.assets/n_queens_cols_diagonals.png",
"title": "Tracking queen constraints with three Boolean arrays",
"explanation": "With the three Boolean arrays cols, diags1, and diags2, column and diagonal conflicts can be checked in constant time; in general, an n×n board has n columns, with 2n − 1 main diagonals and antidiagonals each."
}
],
"tables": [
{
"caption": "Indexing rules for the constraint arrays",
"headers": [
"Array",
"Length",
"Index for candidate square",
"Index set to T in this example"
],
"rows": [
[
"cols",
"n = 4",
"col",
"1"
],
[
"diags1",
"2n−1 = 7",
"row−col+n−1",
"3"
],
[
"diags2",
"2n−1 = 7",
"row+col",
"2"
]
],
"row_header": 0
},
{
"caption": "Current values across the three arrays",
"headers": [
"Array index",
"cols",
"diags1",
"diags2"
],
"rows": [
[
"0",
"F",
"F",
"F"
],
[
"1",
"T",
"F",
"F"
],
[
"2",
"F",
"F",
"T"
],
[
"3",
"F",
"T",
"F"
],
[
"4",
"No such index",
"F",
"F"
],
[
"5",
"No such index",
"F",
"F"
],
[
"6",
"No such index",
"F",
"F"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,79 @@
{
"schema_version": 2,
"title": "Queens cannot share a row, column, or diagonal",
"summary": "The left board shows the 11 squares blocked along the row, column, and two diagonals of a single queen, while the right board shows a valid 4-queens solution satisfying all constraints.",
"context": [
"In chess, a queen attacks pieces at any distance along its horizontal row, vertical column, main diagonal, and antidiagonal. On the 4×4 boards here, rows from top to bottom and columns from left to right are numbered starting at 1 (1-based coordinates)."
],
"description": [
"The left board places a queen at row 2, column 2 ((2, 2)); no other square in the same row, column, or either diagonal may hold another queen, ruling out 11 squares across the four directions.",
"The right board shows a valid arrangement. The two tables below list the squares blocked by the queen on the left board and the column chosen in each row on the right board."
],
"frames": [
{
"id": "source-364",
"book_path": "chapter_backtracking/n_queens_problem.assets/n_queens_constraints.png",
"title": "Queens cannot share a row, column, or diagonal",
"explanation": "A valid arrangement must satisfy all four constraints simultaneously: distinct rows, distinct columns, distinct main diagonals, and distinct antidiagonals; placing one queen per row avoids row conflicts automatically, leaving column and both diagonal constraints to check."
}
],
"tables": [
{
"caption": "Blocked squares for queen at (2,2): 1-based coordinates",
"headers": [
"Direction",
"Attacked squares",
"Square count"
],
"rows": [
[
"Same row",
"(2,1), (2,3), (2,4)",
"3"
],
[
"Same column",
"(1,2), (3,2), (4,2)",
"3"
],
[
"Main diagonal (top-left to bottom-right)",
"(1,1), (3,3), (4,4)",
"3"
],
[
"Antidiagonal (top-right to bottom-left)",
"(1,3), (3,1)",
"2"
]
],
"row_header": 0
},
{
"caption": "Valid arrangement on the right board",
"headers": [
"Row",
"Queen's column"
],
"rows": [
[
"1",
"2"
],
[
"2",
"4"
],
[
"3",
"1"
],
[
"4",
"3"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,147 @@
{
"schema_version": 2,
"title": "Row-by-row trials and pruning conflicting boards",
"summary": "Following the branch that places the first-row queen in column 2, trace row-by-row trials and pruning across 16 candidate boards over four levels to reach the valid column sequence [2, 4, 1, 3].",
"context": [
"Because each row must hold exactly one queen, backtracking places queens row by row from row 1 through row 4 to avoid same-row conflicts automatically; at each level it tries columns 1 through 4 in order and prunes branches that share a column or diagonal with an already placed queen. Rows and columns here are numbered starting at 1."
],
"description": [
"Only the branch with column 2 in the first row is expanded further in the figure, keeping columns 4, 1, and 3 in the next three rows. Continuations from columns 1, 3, and 4 in the first row are marked omitted, meaning they are simply not drawn rather than pruned; in fact, column 3 in the first row leads to the other valid solution [3, 1, 4, 2].",
"The table below lists each candidate square shown in the figure and how it is handled. When a square conflicts with multiple queens at once, the figure and table cite just one conflict—enough to justify pruning rather than listing every conflict. For example, (4,2) is shown conflicting with (3,1) on a main diagonal; checked against all placed queens, it also shares a column with (1,2) and an antidiagonal with (2,4). \"Valid\" in the table means only that the current placement causes no immediate conflict, not that the branch is guaranteed to complete a full solution."
],
"frames": [
{
"id": "source-365",
"book_path": "chapter_backtracking/n_queens_problem.assets/n_queens_placing.png",
"title": "Row-by-row trials and pruning conflicting boards",
"explanation": "Dimmed candidates marked for pruning already violate a constraint, whereas first-row valid branches marked omitted are simply left unexpanded; the two mean different things."
}
],
"tables": [
{
"caption": "Handling of each candidate square: 1-based coordinates",
"headers": [
"Candidate square",
"Placed queens",
"Conflicting queen cited in figure",
"Conflict type",
"Disposition"
],
"rows": [
[
"(1,1)",
"None",
"None",
"No conflict",
"Valid; continuation omitted"
],
[
"(1,2)",
"None",
"None",
"No conflict",
"Keep and continue"
],
[
"(1,3)",
"None",
"None",
"No conflict",
"Valid; continuation omitted"
],
[
"(1,4)",
"None",
"None",
"No conflict",
"Valid; continuation omitted"
],
[
"(2,1)",
"(1,2)",
"(1,2)",
"Antidiagonal",
"Prune"
],
[
"(2,2)",
"(1,2)",
"(1,2)",
"Same column",
"Prune"
],
[
"(2,3)",
"(1,2)",
"(1,2)",
"Main diagonal",
"Prune"
],
[
"(2,4)",
"(1,2)",
"None",
"No conflict",
"Keep and continue"
],
[
"(3,1)",
"(1,2), (2,4)",
"None",
"No conflict",
"Keep and continue"
],
[
"(3,2)",
"(1,2), (2,4)",
"(1,2)",
"Same column",
"Prune"
],
[
"(3,3)",
"(1,2), (2,4)",
"(2,4)",
"Antidiagonal",
"Prune"
],
[
"(3,4)",
"(1,2), (2,4)",
"(2,4)",
"Same column",
"Prune"
],
[
"(4,1)",
"(1,2), (2,4), (3,1)",
"(3,1)",
"Same column",
"Prune"
],
[
"(4,2)",
"(1,2), (2,4), (3,1)",
"(3,1)",
"Main diagonal",
"Prune"
],
[
"(4,3)",
"(1,2), (2,4), (3,1)",
"None",
"No conflict",
"Keep and continue"
],
[
"(4,4)",
"(1,2), (2,4), (3,1)",
"(2,4)",
"Same column",
"Prune"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,52 @@
{
"schema_version": 2,
"title": "Two solutions to the four-queens problem",
"summary": "The left and right boards show the two valid solutions to the 4-queens problem.",
"context": [
"The 4-queens problem asks us to place 4 queens on a 4×4 chessboard so that no two queens share a row, column, or diagonal. The boards in the figure have no numeric labels; for reference below, rows from top to bottom and columns from left to right are numbered starting at 1."
],
"description": [
"The table below gives the queen's column in each row from top to bottom on the left and right boards; all other squares are empty."
],
"frames": [
{
"id": "source-363",
"book_path": "chapter_backtracking/n_queens_problem.assets/solution_4_queens.png",
"title": "Two solutions to the four-queens problem",
"explanation": "Both arrangements place one queen in every row and one in every column; for any pair of queens, the absolute difference between their row numbers differs from the absolute difference between their column numbers, so no two share a main diagonal or an antidiagonal either. The two boards are left-right mirror images of each other and form the complete solution set for 4 queens."
}
],
"tables": [
{
"caption": "Queen column in each row from top to bottom (1-based numbering)",
"headers": [
"Row",
"Left board column",
"Right board column"
],
"rows": [
[
"1",
"2",
"3"
],
[
"2",
"4",
"1"
],
[
"3",
"1",
"4"
],
[
"4",
"3",
"2"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,117 @@
{
"schema_version": 2,
"title": "Recursive choice tree for permutations of distinct elements",
"summary": "Starting from an empty prefix, choose one unused element from [1, 2, 3] in each round and append it to state, producing 6 permutations after three rounds.",
"context": [
"The candidate array is choices = [1, 2, 3], whose three elements are distinct and may each be used only once per permutation. The root node is drawn as three blank slots representing the empty prefix [] before any element is chosen; the blank slots themselves are not element values."
],
"description": [
"The figure expands all recursive branches simultaneously; in actual backtracking execution, after copying and saving state at a leaf node, the code pops the last element and marks it unselected again before trying sibling branches.",
"The choice tree has four levels, from the empty prefix at level 0 to the leaf nodes at level 3. The two tables below look up available next choices by prefix and list all six permutations by index."
],
"frames": [
{
"id": "source-353",
"book_path": "chapter_backtracking/permutations_problem.assets/permutations_i.png",
"title": "Recursive choice tree for permutations of distinct elements",
"explanation": "Across the first, second, and third rounds, each node has 3, 2, and 1 available elements respectively, generating 3 × 2 × 1 = 6 leaf nodes corresponding to all 6 permutations of [1, 2, 3]."
}
],
"tables": [
{
"caption": "Available next choices by prefix",
"headers": [
"Current prefix",
"Available elements",
"Next-level prefixes or leaf result"
],
"rows": [
[
"[]",
"1, 2, 3",
"[1]; [2]; [3]"
],
[
"[1]",
"2, 3",
"[1, 2]; [1, 3]"
],
[
"[2]",
"1, 3",
"[2, 1]; [2, 3]"
],
[
"[3]",
"1, 2",
"[3, 1]; [3, 2]"
],
[
"[1, 2]",
"3",
"[1, 2, 3]"
],
[
"[1, 3]",
"2",
"[1, 3, 2]"
],
[
"[2, 1]",
"3",
"[2, 1, 3]"
],
[
"[2, 3]",
"1",
"[2, 3, 1]"
],
[
"[3, 1]",
"2",
"[3, 1, 2]"
],
[
"[3, 2]",
"1",
"[3, 2, 1]"
]
],
"row_header": 0
},
{
"caption": "All six permutations",
"headers": [
"Result number",
"Complete permutation"
],
"rows": [
[
"1",
"[1, 2, 3]"
],
[
"2",
"[1, 3, 2]"
],
[
"3",
"[2, 1, 3]"
],
[
"4",
"[2, 3, 1]"
],
[
"5",
"[3, 1, 2]"
],
[
"6",
"[3, 2, 1]"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,56 @@
{
"schema_version": 2,
"title": "Pruning already chosen elements in permutations",
"summary": "Along the choice path 1 → 3 → 2, use selected to prune element indices already used in the current permutation prefix.",
"context": [
"The input is choices = [1, 2, 3] (indices 0, 1, 2), with distinct elements, and each element may be used at most once in a permutation. Here state holds the current permutation prefix, while the Boolean array selected tracks by input index whether each element has already been chosen on the current path."
],
"description": [
"The selected array only prevents reusing an index along the current recursive path: descending skips marked indices, and backtracking unmarks them on return, so choosing 1 does not disable 1 permanently—it remains available in other permutation branches.",
"The figure fully expands only the path [] → [1] → [1, 3] → [1, 3, 2]. Pruning marks denote repeated selections that are not entered, such as [1, 1] for choosing element 1 at index 0 again under prefix [1]; ellipses mark valid branches whose continuations are left unexpanded. The table below summarizes choice restrictions and both kinds of branches by prefix."
],
"frames": [
{
"id": "source-354",
"book_path": "chapter_backtracking/permutations_problem.assets/permutations_i_pruning.png",
"title": "Pruning already chosen elements in permutations",
"explanation": "The highlighted path ultimately produces permutation [1, 3, 2]."
}
],
"tables": [
{
"caption": "Choice restrictions along the highlighted path",
"headers": [
"Current prefix",
"Used indices (with values)",
"Remaining available values",
"Value chosen next in figure",
"Pruned and unexpanded branches"
],
"rows": [
[
"[]",
"None",
"1, 2, 3",
"1",
"None pruned; [2] and [3] are valid, continuations unexpanded"
],
[
"[1]",
"0 (value 1)",
"2, 3",
"3",
"Prune [1, 1]; [1, 2] is valid, continuation unexpanded"
],
[
"[1, 3]",
"0 (value 1), 2 (value 3)",
"2",
"2",
"Prune [1, 3, 1] and [1, 3, 3]; no unexpanded branches"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,62 @@
{
"schema_version": 2,
"title": "Equal elements cause duplicate permutations",
"summary": "Expanding two elements of value 1 as separate candidates produces six paths representing only three distinct numeric permutations.",
"context": [
"The input array is choices = [1, 1, 2] at indices 0, 1, and 2. Below, \"first 1\" and \"second 1\" distinguish indices 0 and 1; the figure places a hat over the second 1 as an identity marker, though both have numeric value 1. Each index is used at most once along a path, yet preventing index reuse with selected alone still yields numerically identical permutations."
],
"description": [
"At the top, state has three empty slots. Blue squares denote the first 1, cyan denotes the second 1, and purple denotes 2. Three rounds of choices fill the slots with values from unused indices, expanding into the six leaf nodes in the table below. Entries 3, 4, and 6 have orange borders pointing to \"Duplicate permutations to remove\". Leaf numbers run from left to right, and the kept-versus-duplicate pairings follow from the orange borders and numeric values."
],
"frames": [
{
"id": "source-355",
"book_path": "chapter_backtracking/permutations_problem.assets/permutations_ii.png",
"title": "Equal elements cause duplicate permutations",
"explanation": "Once the element-identity markers are ignored, the six leaf nodes correspond to just three distinct numeric permutations: [1, 1, 2], [1, 2, 1], and [2, 1, 1]."
}
],
"tables": [
{
"caption": "Six leaf nodes and duplicate pairings",
"headers": [
"Leaf number (left to right)",
"Permutation distinguishing element identities",
"Marking in figure and summary"
],
"rows": [
[
"1",
"[first 1, second 1, 2]",
"No orange border, kept"
],
[
"2",
"[first 1, 2, second 1]",
"No orange border, kept"
],
[
"3",
"[second 1, first 1, 2]",
"Orange border, duplicates entry 1"
],
[
"4",
"[second 1, 2, first 1]",
"Orange border, duplicates entry 2"
],
[
"5",
"[2, first 1, second 1]",
"No orange border, kept"
],
[
"6",
"[2, second 1, first 1]",
"Orange border, duplicates entry 5"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,96 @@
{
"schema_version": 2,
"title": "Pruning equal-element branches within a round",
"summary": "Try the repeated value 1 only once per round of choices, pruning duplicate search subtrees in advance.",
"context": [
"The input array is choices = [1, 1, 2] at indices 0, 1, and 2. Below, \"first 1\" and \"second 1\" distinguish indices 0 and 1; the figure places a hat over the second 1 as an identity marker, though both have numeric value 1."
],
"description": [
"Two constraints govern indices and values separately: selected tracks indices already used on the current path, while in the code below a per-round deduplication set duplicated records values not skipped by selected and actually tried in the current round. Each recursive call creates its own duplicated set; backtracking restores selected and state without removing values already recorded in that call's set.",
"The figure explicitly marks only the two same-round prunings that skip the second 1 under the root [] and under prefix [2]. Below, the \"One round of choices for each prefix\" table completes all six nonterminal prefixes, where the \"Skipped due to used index\" column follows from the code rules rather than explicit pruning icons in this figure; the \"Three unique permutations\" table lists each leaf's identity order alongside its numeric values."
],
"frames": [
{
"id": "source-356",
"book_path": "chapter_backtracking/permutations_problem.assets/permutations_ii_pruning.png",
"title": "Pruning equal-element branches within a round",
"explanation": "A single path may still pick both 1s at their two different indices in sequence; within any single round, only one branch is expanded for value 1."
}
],
"tables": [
{
"caption": "One round of choices for each prefix",
"headers": [
"Current prefix",
"Kept candidates",
"Skipped due to used index",
"Skipped due to duplicate value in round"
],
"rows": [
[
"[]",
"first 1, 2",
"None",
"second 1: value 1 already tried in this round"
],
[
"[first 1]",
"second 1, 2",
"first 1: index 0 already on path",
"None"
],
[
"[first 1, second 1]",
"2",
"first 1, second 1: corresponding indices already used",
"None"
],
[
"[first 1, 2]",
"second 1",
"first 1, 2: corresponding indices already used",
"None"
],
[
"[2]",
"first 1",
"2: index 2 already on path",
"second 1: value 1 already tried in this round"
],
[
"[2, first 1]",
"second 1",
"2, first 1: corresponding indices already used",
"None"
]
],
"row_header": 0
},
{
"caption": "Three unique permutations",
"headers": [
"Result number",
"Identity notation distinguishing both 1s",
"Actual numeric result"
],
"rows": [
[
"1",
"[first 1, second 1, 2]",
"[1,1,2]"
],
[
"2",
"[first 1, 2, second 1]",
"[1,2,1]"
],
[
"3",
"[2, first 1, second 1]",
"[2,1,1]"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,96 @@
{
"schema_version": 2,
"title": "Two permutation pruning rules restricting indices and values",
"summary": "Compare side by side the two pruning conditions: no repeated indices along a path (selected) and no repeated values within a round (duplicated).",
"context": [
"The input array is choices = [1, 1, 2] at indices 0, 1, and 2. Below, \"first 1\" and \"second 1\" distinguish indices 0 and 1; the figure places a hat over the second 1 as an identity marker, though both have numeric value 1."
],
"description": [
"Black scissors mark path-index pruning, which forbids reusing an index already on the current path until backtracking makes that index available again. Red scissors mark same-round value pruning: duplicated records only values not skipped by the black scissors and actually chosen during the current call's round, and each recursive call creates a fresh set whose scope differs from selected.",
"Each square node here represents a single choice, the prefix in the table concatenates the choices along the path from the root to that node, and a complete root-to-leaf path forms a permutation. The first table below separates the black and red scissors shown in the figure into two columns; a cell listing multiple candidates corresponds to multiple pruned branches. The second 1 under the root [] and under prefix [2] is pruned by red scissors, while all branches with already used indices are pruned by black scissors. The second table lists the three unique permutations in order."
],
"frames": [
{
"id": "source-357",
"book_path": "chapter_backtracking/permutations_problem.assets/permutations_ii_pruning_summary.png",
"title": "Two permutation pruning rules restricting indices and values",
"explanation": "A single path may still pick both 1s at their two different indices in sequence; within any single round, only one branch is expanded for value 1."
}
],
"tables": [
{
"caption": "One round of choices for each prefix",
"headers": [
"Current prefix",
"Kept candidates",
"Black scissors: skipped due to used index",
"Red scissors: skipped due to duplicate value in round"
],
"rows": [
[
"[]",
"first 1, 2",
"None",
"second 1: value 1 already tried in this round"
],
[
"[first 1]",
"second 1, 2",
"first 1: index 0 already on path",
"None"
],
[
"[first 1, second 1]",
"2",
"first 1, second 1: corresponding indices already used",
"None"
],
[
"[first 1, 2]",
"second 1",
"first 1, 2: corresponding indices already used",
"None"
],
[
"[2]",
"first 1",
"2: index 2 already on path",
"second 1: value 1 already tried in this round"
],
[
"[2, first 1]",
"second 1",
"2, first 1: corresponding indices already used",
"None"
]
],
"row_header": 0
},
{
"caption": "Three unique permutations",
"headers": [
"Result number",
"Identity notation distinguishing both 1s",
"Actual numeric result"
],
"rows": [
[
"1",
"[first 1, second 1, 2]",
"[1,1,2]"
],
[
"2",
"[first 1, 2, second 1]",
"[1,2,1]"
],
[
"3",
"[2, first 1, second 1]",
"[2,1,1]"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,106 @@
{
"schema_version": 2,
"title": "Subset sum I: zeroing the remaining target and index-order pruning",
"summary": "Starting from target 9, subtract candidates level by level while combining start = i with a break when a candidate exceeds the remaining target to output [3, 3, 3] and [4, 5].",
"context": [
"The input consists of the sorted positive integer array choices = [3, 4, 5] (indices 0, 1, 2) and initial target = 9; elements may be chosen repeatedly, and combinations ignore order. The number inside each circular node shows the remaining target balance (9 minus the current prefix sum), reaching a valid subset when reduced to 0."
],
"description": [
"Upon entering a call, if the remaining target is 0, record the current combination and return to the parent call so its loop can continue; otherwise iterate through candidates choices[i] starting from index start, subtract the chosen value from the remaining target, and recurse to the next level. Passing start = i downward allows choosing the current element again while skipping earlier indices (the index-order pruning marked by black scissors in the figure).",
"Because the candidates are sorted in ascending order, within i ≥ start, encountering the first candidate greater than the remaining target triggers an immediate break after comparison, ending the current loop; neither that candidate nor any larger ones after it are entered recursively. Red scissors in the figure mark these out-of-range branches.",
"The figure contains 10 circular nodes with nonnegative remaining targets. The table below lists by prefix the remaining target, the restrictions shown in the figure, and the actual continuation; the remaining target 1 under [4, 4] is left unexpanded in the figure, and its subsequent break is supplied from the code rules."
],
"frames": [
{
"id": "source-360",
"book_path": "chapter_backtracking/subset_sum_problem.assets/subset_sum_i.png",
"title": "Subset sum I: zeroing the remaining target and index-order pruning",
"explanation": "The two paths that reduce the remaining target to 0 are 9 → 6 → 3 → 0 and 9 → 5 → 0, yielding [3, 3, 3] and [4, 5], respectively."
}
],
"tables": [
{
"caption": "Remaining target and choice restrictions by prefix",
"headers": [
"Current prefix",
"Remaining target",
"Available choices",
"Restriction or termination in figure",
"Actual continuation"
],
"rows": [
[
"[]",
"9",
"3, 4, 5",
"None",
"Remaining targets after choosing are 6, 5, and 4, respectively"
],
[
"[3]",
"6",
"3, 4, 5",
"None",
"Remaining targets after choosing are 3, 2, and 1, respectively"
],
[
"[3,3]",
"3",
"3",
"4 and 5 exceed remaining target",
"Choose 3 to reach 0; break upon reaching 4"
],
[
"[3,3,3]",
"0",
"None",
"No further choices",
"Record [3, 3, 3]"
],
[
"[3,4]",
"2",
"None",
"3 is at an earlier index; 4 and 5 exceed remaining target",
"Immediate break starting at 4"
],
[
"[3,5]",
"1",
"None",
"3 and 4 are at earlier indices; 5 exceeds remaining target",
"Immediate break starting at 5"
],
[
"[4]",
"5",
"4, 5",
"3 is at an earlier index",
"Choose 4 to reach 1; choose 5 to reach 0"
],
[
"[4,4]",
"1",
"None",
"Continuation not expanded in figure",
"By the code rules, immediate break starting at 4"
],
[
"[4,5]",
"0",
"None",
"No further choices",
"Record [4, 5]"
],
[
"[5]",
"4",
"None",
"3 and 4 are at earlier indices; 5 exceeds remaining target",
"Immediate break starting at 5"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,98 @@
{
"schema_version": 2,
"title": "Pruning only sums exceeding the target still generates duplicate combinations",
"summary": "Starting from cumulative sum 0 and adding 3, 4, and 5 prunes branches exceeding 9, yet still outputs both duplicate combinations [4, 5] and [5, 4].",
"context": [
"The input consists of the positive integer array choices = [3, 4, 5] and target sum target = 9; each element may be chosen repeatedly, and resulting subsets (combinations) ignore element order."
],
"description": [
"Each circular node shows the cumulative sum of the current prefix (0 at the root). Every round tries adding all candidates 3, 4, and 5: if the new sum exceeds 9 (pruned via a dashed > 9 branch in the figure without forming a new circular node), skip it; if it equals 9, enter the leaf node to record the result and then return to the previous level to continue trying.",
"The search tree has 13 solid circular state nodes. The table below lists each prefix's cumulative sum and next-round choices level by level; reaching a leaf node with sum 9 records one result, and \"enter\" in the parent row refers only to entering that child call. Arrows in the table denote entering the corresponding child node, with the cumulative sum written to the right of the arrow."
],
"frames": [
{
"id": "source-358",
"book_path": "chapter_backtracking/subset_sum_problem.assets/subset_sum_i_naive.png",
"title": "Pruning only sums exceeding the target still generates duplicate combinations",
"explanation": "Although out-of-range pruning stops branches whose sum exceeds 9 promptly, the search still outputs three results—[3, 3, 3], [4, 5], and [5, 4]—where [4, 5] and [5, 4] are duplicate combinations containing the same elements in different orders."
}
],
"tables": [
{
"caption": "Cumulative-sum search tree",
"headers": [
"Current prefix",
"Cumulative sum",
"Next-round choices or termination reason"
],
"rows": [
[
"[]",
"0",
"+3→3; +4→4; +5→5"
],
[
"[3]",
"3",
"+3→6; +4→7; +5→8"
],
[
"[4]",
"4",
"+3→7; +4→8; +5→9, enter [4, 5] (hits 9)"
],
[
"[5]",
"5",
"+3→8; +4→9, enter [5, 4] (hits 9); +5 exceeds target"
],
[
"[3, 3]",
"6",
"+3→9, enter [3, 3, 3] (hits 9); +4 and +5 exceed target"
],
[
"[3, 4]",
"7",
"+3, +4, and +5 all exceed target"
],
[
"[3, 5]",
"8",
"+3, +4, and +5 all exceed target"
],
[
"[4, 3]",
"7",
"+3, +4, and +5 all exceed target"
],
[
"[4, 4]",
"8",
"+3, +4, and +5 all exceed target"
],
[
"[4, 5]",
"9",
"Record result and return"
],
[
"[5, 3]",
"8",
"+3, +4, and +5 all exceed target"
],
[
"[5, 4]",
"9",
"Record result and return"
],
[
"[3, 3, 3]",
"9",
"Record result and return"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,89 @@
{
"schema_version": 2,
"title": "Avoiding duplicate combinations with nondecreasing choice indices",
"summary": "Restrict the next round to choose only from the current index i onward (start = i in the code below), pruning reverse-order duplicate branches that look back to earlier indices.",
"context": [
"The candidate array is choices = [3, 4, 5] (indices 0, 1, 2), where elements may be chosen repeatedly and subsets ignore element order. This figure expands only the first two rounds of choices to compare selection order against duplicate subsets, without expanding a third round or checking the target sum."
],
"description": [
"Combinations ignore element order: picking a larger index first and then going back to a smaller index necessarily duplicates the path that picks the smaller index first and then the larger index. Thus, after choosing 4 we never go back to 3, and after choosing 5 we never go back to 3 or 4.",
"Because this problem allows choosing the same element repeatedly (such as [3, 3, …], [4, 4, …], and [5, 5, …]), selecting index i in the current round must set the next round's starting index to start = i rather than i + 1 so the branch that chooses the current element again is preserved. Trailing ellipses in the figure indicate unexpanded continuations; this figure compares only selection order without checking whether the target sum is reached or exceeded.",
"The three pruned branches are marked with grayed-out boxes, dashed lines, and scissors, and gray arcs along the bottom pair them with the kept prefixes in reverse order. The table below lists all nine two-element prefixes and the three duplicate pairs."
],
"frames": [
{
"id": "source-359",
"book_path": "chapter_backtracking/subset_sum_problem.assets/subset_sum_i_pruning.png",
"title": "Avoiding duplicate combinations with nondecreasing choice indices",
"explanation": "Among the nine prefixes across the first two rounds, the six prefixes with nondecreasing indices are kept, while the three branches that go back to an earlier index are pruned."
}
],
"tables": [
{
"caption": "Nine two-element prefixes and three duplicate pairs",
"headers": [
"Two-element prefix",
"Disposition",
"Reverse-order paired prefix",
"Reason"
],
"rows": [
[
"[3,3,…]",
"Kept",
"No reverse-order counterpart",
"Indices are nondecreasing"
],
[
"[3,4,…]",
"Kept",
"[4,3,…]",
"Indices are nondecreasing"
],
[
"[3,5,…]",
"Kept",
"[5,3,…]",
"Indices are nondecreasing"
],
[
"[4,3,…]",
"Skip earlier index",
"[3,4,…]",
"Produces a duplicate combination with the kept prefix"
],
[
"[4,4,…]",
"Kept",
"No reverse-order counterpart",
"Indices are nondecreasing"
],
[
"[4,5,…]",
"Kept",
"[5,4,…]",
"Indices are nondecreasing"
],
[
"[5,3,…]",
"Skip earlier index",
"[3,5,…]",
"Produces a duplicate combination with the kept prefix"
],
[
"[5,4,…]",
"Skip earlier index",
"[4,5,…]",
"Produces a duplicate combination with the kept prefix"
],
[
"[5,5,…]",
"Kept",
"No reverse-order counterpart",
"Indices are nondecreasing"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,115 @@
{
"schema_version": 2,
"title": "Four pruning conditions for subset sum II",
"summary": "Search the sorted array [4, 4, 5] for subsets summing to 9, combining four pruning conditions to keep only the unique solution [4, 5].",
"context": [
"The input array is choices = [4, 4, 5] at indices 0, 1, and 2. Below, \"first 4\" and \"second 4\" distinguish indices 0 and 1; the figure places a hat over the second 4, though both have numeric value 4. The array is sorted and target = 9; numbers inside the circles show the remaining target."
],
"description": [
"Each index may be used at most once, and subsets ignore order. After selecting index i, the next round begins at start = i + 1, enforcing two rules at once: neither going back to an earlier index (Pruning 2) nor reusing the current index (Pruning 3).",
"When trying the second 4 at the root, its index i = 1 is greater than start = 0, and its value equals the previous candidate’s value, triggering same-round deduplication (Pruning 4). After entering [first 4], the new call has start = 1; now the second 4 has i = 1 equal to start rather than i > start, so it remains selectable. Choosing it leaves a remaining target of 1, and the only candidate afterward is 5, which exceeds the remaining target and triggers an immediate break under Pruning 1.",
"Below, the \"Meanings of the four pruning conditions\" table matches the four colors of scissors in the figure, and the next table lists each prefix and candidate in turn. None of the pruned branches is entered recursively. Pruning 2 and Pruning 3 are skipped directly via start = i + 1—the code never loops over those candidates individually, though the figure draws them for comparison; under [first 4, second 4], choosing the first 4 again is labeled as returning to an earlier index (Pruning 2) in the figure, while its index 0 is also already on the path."
],
"frames": [
{
"id": "source-362",
"book_path": "chapter_backtracking/subset_sum_problem.assets/subset_sum_ii.png",
"title": "Four pruning conditions for subset sum II",
"explanation": "The only path that reduces the remaining target to 0 picks the first 4 and then 5, yielding [4, 5]."
}
],
"tables": [
{
"caption": "Meanings of the four pruning conditions",
"headers": [
"Legend",
"Excluded case"
],
"rows": [
[
"Pruning 1 (red)",
"Selecting the candidate pushes the sum past 9, making remaining target negative"
],
[
"Pruning 2 (blue)",
"Going back to an earlier index produces a duplicate combination in a different order"
],
[
"Pruning 3 (purple)",
"Reusing the current array index that was just selected"
],
[
"Pruning 4 (cyan)",
"Trying another candidate with the same value within the same round"
]
],
"row_header": 0
},
{
"caption": "Candidates and dispositions for each prefix in the figure",
"headers": [
"Prefix and illustrated candidate",
"Remaining target before candidate",
"Outcome or pruning reason"
],
"rows": [
[
"[]: candidate first 4",
"9",
"Kept, remaining target 5"
],
[
"[]: candidate second 4",
"9",
"Duplicate value in round, Pruning 4"
],
[
"[]: candidate 5",
"9",
"Kept, remaining target 4"
],
[
"[first 4]: candidate first 4",
"5",
"Reuses current index, Pruning 3"
],
[
"[first 4]: candidate second 4",
"5",
"Distinct index, selectable, remaining target 1"
],
[
"[first 4]: candidate 5",
"5",
"Remaining target 0, record [4, 5]"
],
[
"[first 4, second 4]: candidate first 4",
"1",
"Returns to earlier index, shown as Pruning 2"
],
[
"[first 4, second 4]: candidate second 4",
"1",
"Reuses current index, Pruning 3"
],
[
"[first 4, second 4]: candidate 5",
"1",
"Exceeds remaining target, Pruning 1"
],
[
"[5]: candidates first 4, second 4",
"4",
"Returns to earlier index, Pruning 2"
],
[
"[5]: candidate 5",
"4",
"Reuses current index, Pruning 3"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,20 @@
{
"schema_version": 2,
"title": "Equal candidates introduce new duplicate combinations",
"summary": "Two elements of value 4 in the candidate array create duplicate subset branches with identical contents within the same round of choices.",
"context": [
"The input array is choices = [4, 4, 5] at indices 0, 1, and 2. Below, \"first 4\" and \"second 4\" distinguish indices 0 and 1; the figure places a hat over the second 4, though both have numeric value 4. Subset sum II requires using each index at most once and producing no duplicate subsets. This figure initially reuses the subset sum I selection rule—passing start = i to the next round so the current index may be chosen again—to illustrate the problem caused by equal candidates."
],
"description": [
"At the top is choices. Starting from the empty state, the two-level partial search tree chooses the first 4, the second 4, or 5 in the first round; in the second round, it tries all three candidates again only under [first 4, …]. In both places, the third branch is labeled only +5 without writing out its prefix.",
"The first gray arc connects [first 4, …] with [second 4, …], and the second connects [first 4, first 4, …] with [first 4, second 4, …], both labeled \"Duplicate subsets\". The first pair shares the numeric prefix [4, …], and the second pair shares [4, 4, …]. Moreover, choosing the first 4 again reuses index 0, which is itself disallowed under the rules of subset sum II."
],
"frames": [
{
"id": "source-361",
"book_path": "chapter_backtracking/subset_sum_problem.assets/subset_sum_ii_repeat.png",
"title": "Equal candidates introduce new duplicate combinations",
"explanation": "Eliminating duplicates in subset sum II requires both forbidding reuse of the same index along a path and trying equal-valued candidates only once within the same round, while still allowing the two 4s at distinct indices to be chosen in different rounds along the same path."
}
]
}

View File

@@ -0,0 +1,18 @@
{
"schema_version": 2,
"title": "Single-level loop",
"summary": "Use initialization, condition checking, and updating to control repeated task execution.",
"context": [
"The flowchart sums the integers from 1 to n for a positive integer n: the running sum starts at 0, and each \"Task\" adds the current i to that sum."
],
"description": [],
"result": "When the task executes, i takes the values 1 through n in turn for n executions in total; once updated to i = n + 1, the condition is false and the loop ends.",
"frames": [
{
"id": "source-19",
"book_path": "chapter_computational_complexity/iteration_and_recursion.assets/iteration.png",
"title": "Single-level loop",
"explanation": "First initialize i = 1, then test i ≤ n. When true, execute the task, increment i by 1, and loop directly back to the condition check; when false, exit. Initialization runs only once before entering the loop rather than resetting i to 1 on every iteration."
}
]
}

View File

@@ -0,0 +1,18 @@
{
"schema_version": 2,
"title": "Two-level nested loop",
"summary": "Each iteration of the outer loop reruns the entire inner loop from start to finish, determining the total number of task executions.",
"context": [
"Here n is a positive integer, i controls the outer loop, and j controls the inner loop."
],
"description": [],
"result": "Every value of i runs through the full range j = 1 to n, so the task executes n × n = n² times in total.",
"frames": [
{
"id": "source-20",
"book_path": "chapter_computational_complexity/iteration_and_recursion.assets/nested_iteration.png",
"title": "Two-level nested loop",
"explanation": "First set i = 1 and test i ≤ n. When true, enter the inner loop, reset j = 1, and test j ≤ n: if true, execute the task, increment j by 1, and return to the inner check; if false, exit the inner loop, increment i by 1, and return to the outer check. Whenever the outer condition still holds, the next round starts over at j = 1; the entire process ends only when the outer condition becomes false."
}
]
}

View File

@@ -0,0 +1,58 @@
{
"schema_version": 2,
"title": "Ordinary recursive summation",
"summary": "Reduce the summation problem down to the base case first, then add level by level on the way back up.",
"context": [
"Here n is a positive integer. The left column, \"Recurse downward\", shows the calls, and the right column, \"Return upward\", shows the corresponding return expressions, with ellipses standing in for intermediate calls. The table below retains the top and bottom levels shown in the figure; small values of n pass only through the levels actually needed."
],
"description": [],
"result": "After accumulating level by level, the initial call recur(n) returns 1 + 2 + … + n.",
"frames": [
{
"id": "source-21",
"book_path": "chapter_computational_complexity/iteration_and_recursion.assets/recursion_sum.png",
"title": "Ordinary recursive summation",
"explanation": "Call recur(n) invokes recur(n - 1), decreasing the argument by 1 at each level until recur(1). At that row, the figure marks \"Reach the base case\" with a rightward arrow into the return phase. Call recur(1) returns 1; recur(2) receives 1 and computes 2 + 1 = 3; recur(3) receives 3 and computes 3 + 3 = 6. In general, recur(k) must wait for its child call to return before adding its own parameter k, so additions happen during the return phase."
}
],
"tables": [
{
"caption": "Calls and return expressions in the figure",
"headers": [
"Downward recursive call",
"Upward return expression"
],
"rows": [
[
"recur(n)",
"n+((n−1)+…+2+1)"
],
[
"recur(n−1)",
"(n−1)+((n−2)+…+2+1)"
],
[
"Intermediate calls",
"Omitted"
],
[
"recur(4)",
"4+(3+2+1)"
],
[
"recur(3)",
"3+(2+1)"
],
[
"recur(2)",
"2+(1)"
],
[
"recur(1), base case",
"1"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,19 @@
{
"schema_version": 2,
"title": "Recursion depth of recursive summation",
"summary": "Highlight the number of active call levels accumulated before recursive summation hits the base case.",
"context": [
"Here n is a positive integer; recursion depth is the maximum number of simultaneously unreturned call levels."
],
"description": [
"Under the left heading \"Recurse downward\", the call chain runs recur(n) → recur(n - 1) → … → recur(4) → recur(3) → recur(2) → recur(1), spanned on the left by a brace labeled \"Recursion depth n\". At the bottom, the arrow \"Reach the base case\" leads to the right column \"Return upward\", where the returning additions are dimmed to highlight call accumulation on the left."
],
"frames": [
{
"id": "source-22",
"book_path": "chapter_computational_complexity/iteration_and_recursion.assets/recursion_sum_depth.png",
"title": "Recursion depth of recursive summation",
"explanation": "Upon reaching recur(1), every outer call is waiting for its child's result, so n stack frames—including the top-level call—coexist at once. Only afterward do calls return starting from 1, adding each level's parameter and releasing its stack frame one by one. That peak count of active calls sets the recursion depth to n and the stack space to O(n)."
}
]
}

View File

@@ -0,0 +1,58 @@
{
"schema_version": 2,
"title": "Fibonacci recursion tree",
"summary": "Recursive branches repeatedly solve identically named subproblems, showing why naive recursion performs so much redundant work.",
"context": [
"In the figure, f(k) corresponds to fib(k) in the chapter code. The base cases are f(1) = 0 and f(2) = 1; for k > 2, it computes f(k - 1) + f(k - 2)."
],
"description": [
"The figure expands only the first few levels without labeling a total height. For small n, some branches reach f(1) or f(2) earlier and stop rather than continuing through every symbolic level drawn."
],
"result": "Actual branches stop at base cases, so not every level doubles indefinitely, yet repeated expansion still makes the call count of naive recursion grow exponentially with n. Counting levels strictly from the chapter code with the root as level 1, the longest call chain has n - 1 levels when n ≥ 2 (for instance, 2 levels when n = 3) and just the root level when n = 1. Calling the height n in the text expresses linear order of growth in n rather than the exact level count here.",
"frames": [
{
"id": "source-24",
"book_path": "chapter_computational_complexity/iteration_and_recursion.assets/recursion_tree.png",
"title": "Fibonacci recursion tree",
"explanation": "Every non-base call f(k) branches into a left child call f(k - 1) and a right child call f(k - 2). For example, the root's right child f(n - 2) (level 2) and the f(n - 2) branched on the left of level 3 lie on separate call paths and are each recomputed from scratch rather than automatically merged or reused."
}
],
"tables": [
{
"caption": "Calls at each level in the figure; identical names denote separate calls",
"headers": [
"Level",
"Call nodes (left to right in figure)",
"Count"
],
"rows": [
[
"1",
"f(n)",
"1"
],
[
"2",
"f(n - 1), f(n - 2)",
"2"
],
[
"3",
"f(n - 2), f(n - 3), f(n - 3), f(n - 4)",
"4"
],
[
"4",
"f(n - 3), f(n - 4), f(n - 4), f(n - 5), f(n - 4), f(n - 5), f(n - 5), f(n - 6)",
"8"
],
[
"5",
"Each node from the previous level branches into two ellipses; deeper calls are not drawn explicitly",
"16 ellipses"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,60 @@
{
"schema_version": 2,
"title": "Tail-recursive summation",
"summary": "Use an accumulator to perform addition before each recursive call so the return phase simply passes the result back.",
"context": [
"Initially n is a nonnegative integer and accumulator res = 0; recur(n, res) in the figure corresponds to tail_recur in the code."
],
"description": [
"The left column, \"Recurse downward\", lists the parameter and accumulator at each step, while every row in the right column, \"Return upward\", returns the final sum unchanged. The table below follows the figure's top and bottom calls for larger n with intermediate levels represented by ellipses; smaller n passes only through the parameters actually needed rather than a fixed 7 levels. When n = 0, it immediately returns the initial value 0."
],
"result": "Stack frames can be reused to reduce stack space to O(1) only when the runtime environment supports and enables tail-call optimization; without optimization, stack space remains O(n). Python does not support tail-call optimization by default.",
"frames": [
{
"id": "source-23",
"book_path": "chapter_computational_complexity/iteration_and_recursion.assets/tail_recursion_sum.png",
"title": "Tail-recursive summation",
"explanation": "Starting from recur(n, 0), each step computes res + k first and then calls the next level with k - 1 and the updated accumulator. At k = 1, only the final term 1 remains to be added; the next level k = 0 hits the base case and immediately returns the complete sum. During the return phase, each level merely forwards that same result without performing further additions."
}
],
"tables": [
{
"caption": "Accumulator values during downward calls in the figure",
"headers": [
"Current parameter k",
"Accumulated res"
],
"rows": [
[
"n",
"0"
],
[
"n−1",
"n"
],
[
"Intermediate calls",
"Omitted"
],
[
"3",
"n+…+5+4"
],
[
"2",
"n+…+5+4+3"
],
[
"1",
"n+…+5+4+3+2"
],
[
"0",
"n + … + 5 + 4 + 3 + 2 + 1, complete sum"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,51 @@
{
"schema_version": 2,
"title": "Growth trends of common space complexity classes",
"summary": "Compare how five space complexity classes grow as input size increases.",
"context": [
"The horizontal axis shows input size n with ticks from 1 to 14; the vertical axis shows memory usage with no numeric capacity ticks. This schematic compares asymptotic growth trends rather than exact byte counts or unscaled function values."
],
"description": [
"The table below orders the five curves from lowest to highest at the right edge of the plot, matching the upward arrow on the right labeled \"Lower → higher; better → worse\"."
],
"frames": [
{
"id": "source-34",
"book_path": "chapter_computational_complexity/space_complexity.assets/space_complexity_common_types.png",
"title": "Growth trends of common space complexity classes",
"explanation": "At small sizes some schematic curves cross—for instance, between ticks 2 and 6 the logarithmic curve sits slightly above the linear line. What the plot conveys is the growth trend for sufficiently large n: constant stays flat, logarithmic grows slowly, and exponential eventually grows fastest; early crossings cannot be used to read off exact memory usage for specific inputs."
}
],
"tables": [
{
"caption": "Five space complexity classes and curve shapes",
"headers": [
"Complexity (low to high at right edge)",
"Shape in figure"
],
"row_header": 0,
"rows": [
[
"Constant O(1)",
"Green horizontal line just above the horizontal axis, unchanged as n grows"
],
[
"Logarithmic O(log n)",
"Cyan curve rising slowly with gradually flattening slope"
],
[
"Linear O(n)",
"Blue straight line rising at a constant slope"
],
[
"Quadratic O(n²)",
"Orange curve bending upward with increasingly steep slope"
],
[
"Exponential O(2ⁿ)",
"Red curve staying near the bottom around ticks 1 to 8 before shooting upward steeply"
]
]
}
]
}

View File

@@ -0,0 +1,47 @@
{
"schema_version": 2,
"title": "Space required to store an n-level perfect binary tree",
"summary": "Storing an entire n-level perfect binary tree requires counting every retained node, not just the recursive call stack.",
"context": [
"Here n is a positive integer, and the figure corresponds to the tree constructed and retained by build_tree. Each circle represents one node occupying constant space, connected by arrows to its left and right children; the brace on the right reads \"A total of n levels\"."
],
"description": [
"The figure draws the first 3 levels and then extends 8 arrows from the 4 nodes on level 3 into ellipses to indicate further levels. The right column, \"Total nodes at each level\", writes powers 2⁰, 2¹, 2², …, 2ⁿ⁻¹. The table below supplies level numbers, decimal counts for the opening levels, and spoken forms of the powers."
],
"frames": [
{
"id": "source-37",
"book_path": "chapter_computational_complexity/space_complexity.assets/space_complexity_exponential.png",
"title": "Space required to store an n-level perfect binary tree",
"explanation": "At the bottom, summing across levels gives 2⁰ + 2¹ + 2² + … + 2ⁿ⁻¹ = 2ⁿ - 1—that is, one less than 2 to the power n. Because new nodes remain linked into the tree via left and right pointers instead of being destroyed when the calls that created them return, all of these nodes occupy memory simultaneously. Even though the recursive call stack is only O(n) deep, the tree as a whole still requires O(2ⁿ) space, which is the conclusion pointed to at the bottom."
}
],
"tables": [
{
"caption": "Node count at each level of the perfect binary tree",
"headers": [
"Level (root is level 1)",
"Total nodes"
],
"row_header": 0,
"rows": [
[
"1",
"2⁰ = 1"
],
[
"2",
"2¹ = 2"
],
[
"3",
"2² = 4"
],
[
"n",
"2ⁿ⁻¹, that is, 2 raised to the exponent (n minus 1)"
]
]
}
]
}

View File

@@ -0,0 +1,18 @@
{
"schema_version": 2,
"title": "Stack space of recursive calls",
"summary": "Stack space depends on how many calls remain active at once, as each nested recursive call adds a stack frame.",
"context": [
"Here n is a positive integer, counted below under standard execution without tail-call optimization."
],
"description": [],
"result": "Each level uses constant local space, and at maximum depth n levels coexist simultaneously for O(n) peak stack space; releasing frames afterward one by one does not reduce the peak already reached.",
"frames": [
{
"id": "source-35",
"book_path": "chapter_computational_complexity/space_complexity.assets/space_complexity_recursive_linear.png",
"title": "Stack space of recursive calls",
"explanation": "The left column, \"Recurse downward\", steps down by 1 from linear_recur(n) to the base case linear_recur(1), spanned by a brace labeled \"Recursion depth n\". Because outer calls wait for inner calls to finish, n stack frames coexist at the deepest point; control then unwinds up the right column, \"Return upward\", freeing each level's stack frame only as it returns. Although the right column writes return 0 whereas the current Python code uses a bare return (returning None), that difference does not affect the stack-space count."
}
]
}

View File

@@ -0,0 +1,51 @@
{
"schema_version": 2,
"title": "Retaining an array at each recursive level creates quadratic space",
"summary": "When every recursive level also holds a local array, peak space sums the array lengths across all simultaneously unreturned levels.",
"context": [
"Here n is a positive integer. Whenever k > 0, each call quadratic_recur(k) allocates an array nums of length k before calling quadratic_recur(k - 1). The figure omits the final call quadratic_recur(0), which allocates no array, simplifying the base case and return onto the row for argument 1; the actual code returns immediately at argument 0."
],
"description": [
"From left to right, the figure arranges three columns—\"Length of array nums\", \"Recurse downward\", and \"Return upward\"—connecting each array length horizontally to its call. A brace labeled \"Recursion depth n\" spans the n levels that allocate arrays, with ellipses for intermediate calls. At the row for argument 1, an arrow labeled \"Reach the base case\" crosses to the right column, where return 0 entries are linked upward."
],
"frames": [
{
"id": "source-36",
"book_path": "chapter_computational_complexity/space_complexity.assets/space_complexity_recursive_quadratic.png",
"title": "Retaining an array at each recursive level creates quadratic space",
"explanation": "While each upper call waits for its lower call to return, its local array remains live in memory. At the bottom, summing their lengths gives 1 + 2 + … + (n - 1) + n = n(n + 1)/2, pointing to Quadratic O(n²). Although the actual code adds one extra stack frame at argument 0 without allocating an array, the O(n) call-stack overhead does not change the O(n²) peak space dominated by those arrays."
}
],
"tables": [
{
"caption": "Arrays retained across active recursive levels",
"headers": [
"Call",
"Length of nums"
],
"row_header": 0,
"rows": [
[
"quadratic_recur(n)",
"n"
],
[
"quadratic_recur(n−1)",
"n−1"
],
[
"Intermediate calls",
"Omitted"
],
[
"quadratic_recur(2)",
"2"
],
[
"quadratic_recur(1)",
"1"
]
]
}
]
}

View File

@@ -0,0 +1,17 @@
{
"schema_version": 2,
"title": "Which memory regions space complexity usually counts",
"summary": "Divide the memory involved in running an algorithm into three categories, with a brace marking the scope normally counted in space complexity.",
"context": [],
"description": [
"From left to right, three boxes connected by rightward arrows trace the flow of receiving input, storing intermediate state, and producing output. On the left, \"Input space\" contains \"Input data\"; in the middle, \"Auxiliary space\" lists \"Temporary data\", \"Stack frames\", and \"Instructions\"; on the right, \"Output space\" contains \"Output data\"."
],
"frames": [
{
"id": "source-33",
"book_path": "chapter_computational_complexity/space_complexity.assets/space_types.png",
"title": "Which memory regions space complexity usually counts",
"explanation": "The upper brace spans only auxiliary space and output space, labeled \"Scope usually included in space complexity\" and excluding input space. Under the chapter's convention, instruction space inside auxiliary space is typically omitted as well, focusing the count on temporary data, stack frames, and output data."
}
]
}

View File

@@ -0,0 +1,19 @@
{
"schema_version": 2,
"title": "Asymptotic upper bound: inequality beyond a threshold",
"summary": "The two curves show how to read an asymptotic upper bound. Once the input size n exceeds the threshold, T(n) stays at or below c times f(n).",
"context": [
"The horizontal axis shows input size n with ticks from 0 to 14; the vertical axis shows function value with no numeric ticks. The blue curve is the operation count T(n), and the orange curve is a candidate function f(n) scaled by a positive constant c, written c·f(n); no explicit formulas are given."
],
"description": [
"A vertical green dashed line at n₀ marks the intersection of the two curves between ticks 7 and 8. Across ticks 1 to 7, the blue curve fluctuates above the orange curve; past n₀, the orange curve stays strictly above the blue curve as both continue rising."
],
"frames": [
{
"id": "source-26",
"book_path": "chapter_computational_complexity/time_complexity.assets/asymptotic_upper_bound.png",
"title": "Asymptotic upper bound: inequality beyond a threshold",
"explanation": "The condition stated at the bottom is that there exist a positive constant c and a threshold n₀ such that T(n) ≤ c·f(n) for all n > n₀, written T(n) = O(f(n)), making f(n) an asymptotic upper bound on T(n). Having T(n) exceed c·f(n) before n₀ does not affect this conclusion, and the curves do not have to coincide at every input."
}
]
}

View File

@@ -0,0 +1,51 @@
{
"schema_version": 2,
"title": "Growth trends of five common time complexity classes",
"summary": "Compare how five time complexity classes grow as input size increases.",
"context": [
"The horizontal axis shows input size n with ticks from 1 to 14; the vertical axis shows the number of operations T(n) with no numeric ticks. The curves illustrate asymptotic growth trends rather than measured operation counts from a program or unscaled function values."
],
"description": [
"The table below orders the curves from lowest to highest at the right edge of the plot, matching the upward arrow on the right labeled \"Lower → higher; better → worse\"."
],
"frames": [
{
"id": "source-27",
"book_path": "chapter_computational_complexity/time_complexity.assets/time_complexity_common_types.png",
"title": "Growth trends of five common time complexity classes",
"explanation": "In the left portion of the plot several curves cross—for instance, the red exponential curve starts out below both the blue linear line and the orange quadratic curve before overtaking them. Those intersections are purely schematic and cannot be used to read off exact operation counts or crossover thresholds for specific inputs. What the plot conveys is that for sufficiently large n, lower complexity classes grow more slowly in operation count."
}
],
"tables": [
{
"caption": "Five time complexity classes and curve shapes",
"headers": [
"Complexity (low to high at right edge)",
"Shape in figure"
],
"row_header": 0,
"rows": [
[
"Constant O(1)",
"Green horizontal line whose operation count does not change with n"
],
[
"Logarithmic O(log n)",
"Cyan curve rising slowly with gradually decreasing slope"
],
[
"Linear O(n)",
"Blue straight line rising at a constant slope"
],
[
"Quadratic O(n²)",
"Orange curve bending upward with increasingly steep slope"
],
[
"Exponential O(2ⁿ)",
"Red curve staying near the bottom early on and rising steeply afterward"
]
]
}
]
}

View File

@@ -0,0 +1,45 @@
{
"schema_version": 2,
"title": "Loop structures and operation counts",
"summary": "Compare how workload grows across a single operation, a single loop, and a nested two-level loop.",
"context": [],
"description": [
"Each small square represents 1 elementary operation, and each surrounding loop box indicates the scope repeated."
],
"frames": [
{
"id": "source-28",
"book_path": "chapter_computational_complexity/time_complexity.assets/time_complexity_constant_linear_quadratic.png",
"title": "Loop structures and operation counts",
"explanation": "A double enclosure represents nesting: for every 1 iteration of the outer loop, the inner loop runs all n iterations in full, so the counts multiply to n × n rather than adding as they would for two sequential loops."
}
],
"tables": [
{
"caption": "Workloads across loop structures",
"headers": [
"Structure",
"Elementary operation count",
"Time complexity"
],
"rows": [
[
"No loop",
"1",
"Constant O(1)"
],
[
"Single loop of n iterations",
"n",
"Linear O(n)"
],
[
"Two nested loops of n iterations each",
"n×n=n²",
"Quadratic O(n²)"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,47 @@
{
"schema_version": 2,
"title": "Recursion tree where every node branches into two",
"summary": "Each level down the recursion tree doubles the node count, so total workload sums across all levels.",
"context": [
"Each square represents one operation, with the root counted as level 1. The top heading reads \"Recursion tree — each node branches into two\", and the right brace reads \"A total of n levels\" for a positive integer n."
],
"description": [
"The figure draws 1, 2, and 4 nodes on the first three levels, each non-leaf node branching to two children. Below level 3, 8 arrows lead into ellipses, and the bottom row draws 8 squares separated by ellipses purely schematically rather than fixing the bottom level at 8 nodes. The right column writes each level's count as a power of 2, while the decimal values in the table below are supplied by calculation. For n ≤ 3, only the levels that actually exist apply, and row n in the table coincides with the corresponding earlier row."
],
"frames": [
{
"id": "source-29",
"book_path": "chapter_computational_complexity/time_complexity.assets/time_complexity_exponential.png",
"title": "Recursion tree where every node branches into two",
"explanation": "Summing all levels at the bottom gives 2⁰ + 2¹ + … + 2ⁿ⁻¹ = 2ⁿ - 1—that is, one less than 2 to the power n—giving O(2ⁿ). For the iterative cell-division code preceding the figure, level k represents the divisions performed in round k: n rounds perform 2ⁿ - 1 divisions in total to yield 2ⁿ final cells, which are not drawn as an extra row of operations. For exp_recur(n) following the figure, each square represents a call as the argument steps from n down to 1 across n levels, counting 1 per call and returning the same total."
}
],
"tables": [
{
"caption": "Operations at each level of the recursion tree",
"headers": [
"Level (root is level 1)",
"Node count"
],
"row_header": 0,
"rows": [
[
"1",
"2⁰ = 1"
],
[
"2",
"2¹ = 2"
],
[
"3",
"2² = 4"
],
[
"n",
"2ⁿ⁻¹, that is, 2 raised to the exponent (n minus 1)"
]
]
}
]
}

View File

@@ -0,0 +1,57 @@
{
"schema_version": 2,
"title": "Level-by-level choices in permutations and factorial growth",
"summary": "Fixing one more position in a permutation leaves one fewer available element, so multiplying branching counts across levels yields the total number of permutations.",
"context": [
"All n elements are distinct. The gray root node at the top precedes any choice, and each dashed-box level below fixes the next position. The right brace labeled \"A total of n levels\" spans only the n choice levels beneath the root, excluding the root itself."
],
"description": [
"The left column, \"Number of branches at each level\", shows how many child branches leave each node of the preceding level, while the right column, \"Number of nodes at each level\", gives the total nodes on that level. Intermediate levels are represented by ellipses; small values of n pass only through the choice levels actually needed, so the final row in the table may coincide with an earlier row."
],
"frames": [
{
"id": "source-32",
"book_path": "chapter_computational_complexity/time_complexity.assets/time_complexity_factorial.png",
"title": "Level-by-level choices in permutations and factorial growth",
"explanation": "At the bottom, n × (n - 1) × … × 1 = n! counts the green leaf nodes on the lowest level: each leaf corresponds to one complete permutation and contributes one base-case count to factorial_recur, so n! is not the total node count of the entire tree. Even including the root and all internal levels, the total node count stays strictly less than 3 times n!. Although each call in the code runs a loop, every loop iteration traverses exactly one edge to a child call, and the number of edges in the tree equals total nodes minus 1, keeping the overall work O(n!). This bound assumes constant work per edge and excludes copying full permutations."
}
],
"tables": [
{
"caption": "Branching factors and node counts across permutation choice levels",
"headers": [
"Choice level",
"Branches per node from previous level",
"Total nodes on level"
],
"row_header": 0,
"rows": [
[
"1",
"n",
"n"
],
[
"2",
"n−1",
"n(n−1)"
],
[
"3",
"n−2",
"n(n−1)(n−2)"
],
[
"Intermediate levels (if any)",
"Decreases by 1 each level",
"Continues multiplying"
],
[
"n, final level",
"1",
"n!"
]
]
}
]
}

View File

@@ -0,0 +1,47 @@
{
"schema_version": 2,
"title": "Logarithmic growth from halving at each step",
"summary": "Halving the remaining length in each round pairs every retained array state one-to-one with a single operation at that level.",
"context": [
"Let n be a nonnegative integer power of 2. From left to right, the three columns are headed \"Remaining array length\", \"Input array length: n — halved at each level\", and \"Each level has 1 operation\". Dark green cells and outlines mark the retained subarray, while light gray cells mark excluded portions."
],
"description": [
"Ellipses at the top stand for earlier halving steps, followed by the final four levels drawn explicitly. On the right, each level has one light green operation box linked downward by arrows; the rightmost brace reads \"A total of log₂n + 1 levels\", and the bottom summary likewise writes log₂n + 1 total operations, pointing to O(log n)."
],
"frames": [
{
"id": "source-30",
"book_path": "chapter_computational_complexity/time_complexity.assets/time_complexity_logarithmic.png",
"title": "Logarithmic growth from halving at each step",
"explanation": "Halving n down to 1 takes log₂ n (log base 2 of n) halving steps, which is the exact count returned by while n > 1 in the code; the figure also counts the final length-1 level as 1 operation, giving one more level than the count returned by the code. For instance, 8 → 4 → 2 → 1 has 3 halvings across 4 state levels. That constant difference does not change the logarithmic complexity O(log n). The ellipses and four rows illustrate general n; small inputs pass only through the levels that actually exist."
}
],
"tables": [
{
"caption": "Retained subarrays across the final four levels in the figure",
"headers": [
"Remaining length",
"Retained slice in an 8-cell array"
],
"row_header": 0,
"rows": [
[
"8",
"All 8 cells"
],
[
"4",
"Rightmost 4 cells"
],
[
"2",
"Rightmost 2 cells"
],
[
"1",
"Rightmost 1 cell"
]
]
}
]
}

View File

@@ -0,0 +1,63 @@
{
"schema_version": 2,
"title": "Per-level workload of a divide-and-conquer tree",
"summary": "Doubling the number of subproblems while halving each subproblem's work keeps the total work per level constant.",
"context": [
"Let n be a nonnegative integer power of 2. Each box in the figure represents a subproblem whose operation count equals its current size; starting from the root, every subproblem splits into two equal halves from one level to the next."
],
"description": [
"The right side totals the operations at each level. The bottom row draws only 4 boxes separated by ellipses to represent all n leaves. The table below describes the levels for general n; for small n, intermediate levels may be absent and the leaf level may coincide with an earlier row rather than there always being 5 fixed levels."
],
"frames": [
{
"id": "source-31",
"book_path": "chapter_computational_complexity/time_complexity.assets/time_complexity_logarithmic_linear.png",
"title": "Per-level workload of a divide-and-conquer tree",
"explanation": "Numbering the root as level 0, level d has 2^d (2 to the power d) subproblems performing n / 2^d operations each, whose product is always n. At the leaf level each subproblem has size 1, so 2^d = n and d = log₂ n (log base 2 of n); from level 0 through level log₂ n there are log₂ n + 1 levels in total. At the bottom of the diagram, multiplying n operations per level by the total number of levels gives n(log₂ n + 1) = n log₂ n + n, which is O(n log n)."
}
],
"tables": [
{
"caption": "Total operations at each level in the figure",
"headers": [
"Level",
"Number of subproblems",
"Operations per subproblem",
"Level total"
],
"rows": [
[
"Root level",
"1",
"n",
"n"
],
[
"Next level",
"2",
"n/2",
"n"
],
[
"Second level down",
"4",
"n/4",
"n"
],
[
"Intermediate levels (if any)",
"Continues doubling",
"Continues halving",
"n"
],
[
"Leaf level",
"n",
"1",
"n"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,47 @@
{
"schema_version": 2,
"title": "Algorithms A, B, and C: actual runtime versus growth trend",
"summary": "Compare the runtime curves of algorithms A, B, and C to distinguish actual elapsed time from asymptotic growth trend.",
"context": [
"The horizontal axis shows input size n with ticks from 0 to 9; the vertical axis shows algorithm running time with visible ticks at 0, 5, 10, an ellipsis, and 1000000. Because the vertical axis compresses the span between 10 and 1000000, vertical distances between curves are not drawn to a uniform scale."
],
"description": [
"All three algorithms execute the same print operation. In the table below, print counts come from the chapter code, while curve colors and positions come from the figure."
],
"frames": [
{
"id": "source-25",
"book_path": "chapter_computational_complexity/time_complexity.assets/time_complexity_simple_example.png",
"title": "Algorithms A, B, and C: actual runtime versus growth trend",
"explanation": "Neither A nor C changes its operation count as n grows, so both belong to O(1) despite their large difference in runtime; B grows linearly with n and belongs to O(n). Extrapolating by print count, B and C intersect at n = 1000000, beyond the horizontal range plotted."
}
],
"tables": [
{
"caption": "Print counts and plotted curves by algorithm",
"headers": [
"Algorithm",
"Print count",
"Plotted runtime curve"
],
"row_header": 0,
"rows": [
[
"A",
"1",
"Green horizontal line between 0 and 5 on the vertical axis"
],
[
"B",
"n",
"Blue slanted line starting at the origin, intersecting A at n = 1 and approaching tick 10 at n = 9"
],
[
"C",
"1000000",
"Orange horizontal line at tick 1000000 on the vertical axis"
]
]
}
]
}

View File

@@ -0,0 +1,804 @@
{
"schema_version": 2,
"title": "ASCII characters and code table",
"summary": "Look up the binary representation by decimal code or character, and distinguish control characters from printable characters.",
"context": [
"ASCII uses 7 bits to represent 128 characters, with codes ranging from 0 to 127. The figure displays binary values as 8-bit single bytes grouped into nibbles of 4 bits, with the highest bit fixed at 0; the table below merges the figure's four column panels into a single complete table ordered by increasing decimal code."
],
"description": [
"By code range: 0 to 31 and 127 are control characters, where 127 is DEL for delete (left blank in the figure's meaning column); 32 is the space character SP; 48 to 57 are the digits 0 to 9; 65 to 90 are uppercase letters A to Z; and 97 to 122 are lowercase letters a to z. Printable punctuation and symbols occupy 33 to 47, 58 to 64, 91 to 96, and 123 to 126.",
"The table’s meaning column uses the labels in the English figure. Code 14, SO (Shift out), selects an alternate character set; code 15, SI (Shift in), switches back to the original set. Code 27, ESC (Escape), can introduce an escape sequence. Codes 10 (LF, Line feed), 12 (FF, Form feed), and 13 (CR, Carriage return) control line breaks, page breaks, and returning to the start of a line, respectively.",
"A character glyph differs from its numeric code: the digit character 0 has code 48 (binary 0011 0000), whereas code 0 is the null character NUL (binary 0000 0000); both also differ from the space character SP (32) and the delete character DEL (127)."
],
"frames": [
{
"id": "source-43",
"book_path": "chapter_data_structure/character_encoding.assets/ascii_table.png",
"title": "ASCII characters and code table",
"explanation": "For the digit characters 0 to 9, the upper four bits are always 0011 and the lower four bits run from 0000 to 1001. Uppercase and lowercase forms of the same letter differ by 32, changing only the 6th bit from the right (weight 32): A is 65 (binary 0100 0001) and a is 97 (binary 0110 0001). For instance, to look up a newline, locate LF at decimal row 10 in the table below."
}
],
"tables": [
{
"caption": "Complete ASCII code table (matching every row in the figure)",
"headers": [
"Decimal",
"Binary",
"Character",
"Meaning (shown in figure)"
],
"rows": [
[
"0",
"0000 0000",
"NUL",
"Null"
],
[
"1",
"0000 0001",
"SOH",
"Start of heading"
],
[
"2",
"0000 0010",
"STX",
"Start of text"
],
[
"3",
"0000 0011",
"ETX",
"End of text"
],
[
"4",
"0000 0100",
"EOT",
"End of transmission"
],
[
"5",
"0000 0101",
"ENQ",
"Enquiry"
],
[
"6",
"0000 0110",
"ACK",
"Acknowledge"
],
[
"7",
"0000 0111",
"BEL",
"Bell"
],
[
"8",
"0000 1000",
"BS",
"Backspace"
],
[
"9",
"0000 1001",
"HT",
"Horizontal tab"
],
[
"10",
"0000 1010",
"LF",
"Line feed"
],
[
"11",
"0000 1011",
"VT",
"Vertical tab"
],
[
"12",
"0000 1100",
"FF",
"Form feed"
],
[
"13",
"0000 1101",
"CR",
"Carriage return"
],
[
"14",
"0000 1110",
"SO",
"Shift out"
],
[
"15",
"0000 1111",
"SI",
"Shift in"
],
[
"16",
"0001 0000",
"DLE",
"Data link escape"
],
[
"17",
"0001 0001",
"DC1",
"Device control 1"
],
[
"18",
"0001 0010",
"DC2",
"Device control 2"
],
[
"19",
"0001 0011",
"DC3",
"Device control 3"
],
[
"20",
"0001 0100",
"DC4",
"Device control 4"
],
[
"21",
"0001 0101",
"NAK",
"Negative acknowledge"
],
[
"22",
"0001 0110",
"SYN",
"Synchronous idle"
],
[
"23",
"0001 0111",
"ETB",
"End of transmission block"
],
[
"24",
"0001 1000",
"CAN",
"Cancel"
],
[
"25",
"0001 1001",
"EM",
"End of medium"
],
[
"26",
"0001 1010",
"SUB",
"Substitute"
],
[
"27",
"0001 1011",
"ESC",
"Escape"
],
[
"28",
"0001 1100",
"FS",
"File separator"
],
[
"29",
"0001 1101",
"GS",
"Group separator"
],
[
"30",
"0001 1110",
"RS",
"Record separator"
],
[
"31",
"0001 1111",
"US",
"Unit separator"
],
[
"32",
"0010 0000",
"SP",
"Space"
],
[
"33",
"0010 0001",
"!",
""
],
[
"34",
"0010 0010",
"\"",
""
],
[
"35",
"0010 0011",
"#",
""
],
[
"36",
"0010 0100",
"$",
""
],
[
"37",
"0010 0101",
"%",
""
],
[
"38",
"0010 0110",
"&",
""
],
[
"39",
"0010 0111",
"'",
""
],
[
"40",
"0010 1000",
"(",
""
],
[
"41",
"0010 1001",
")",
""
],
[
"42",
"0010 1010",
"*",
""
],
[
"43",
"0010 1011",
"+",
""
],
[
"44",
"0010 1100",
",",
""
],
[
"45",
"0010 1101",
"-",
""
],
[
"46",
"0010 1110",
".",
""
],
[
"47",
"0010 1111",
"/",
""
],
[
"48",
"0011 0000",
"0",
""
],
[
"49",
"0011 0001",
"1",
""
],
[
"50",
"0011 0010",
"2",
""
],
[
"51",
"0011 0011",
"3",
""
],
[
"52",
"0011 0100",
"4",
""
],
[
"53",
"0011 0101",
"5",
""
],
[
"54",
"0011 0110",
"6",
""
],
[
"55",
"0011 0111",
"7",
""
],
[
"56",
"0011 1000",
"8",
""
],
[
"57",
"0011 1001",
"9",
""
],
[
"58",
"0011 1010",
":",
""
],
[
"59",
"0011 1011",
";",
""
],
[
"60",
"0011 1100",
"<",
""
],
[
"61",
"0011 1101",
"=",
""
],
[
"62",
"0011 1110",
">",
""
],
[
"63",
"0011 1111",
"?",
""
],
[
"64",
"0100 0000",
"@",
""
],
[
"65",
"0100 0001",
"A",
""
],
[
"66",
"0100 0010",
"B",
""
],
[
"67",
"0100 0011",
"C",
""
],
[
"68",
"0100 0100",
"D",
""
],
[
"69",
"0100 0101",
"E",
""
],
[
"70",
"0100 0110",
"F",
""
],
[
"71",
"0100 0111",
"G",
""
],
[
"72",
"0100 1000",
"H",
""
],
[
"73",
"0100 1001",
"I",
""
],
[
"74",
"0100 1010",
"J",
""
],
[
"75",
"0100 1011",
"K",
""
],
[
"76",
"0100 1100",
"L",
""
],
[
"77",
"0100 1101",
"M",
""
],
[
"78",
"0100 1110",
"N",
""
],
[
"79",
"0100 1111",
"O",
""
],
[
"80",
"0101 0000",
"P",
""
],
[
"81",
"0101 0001",
"Q",
""
],
[
"82",
"0101 0010",
"R",
""
],
[
"83",
"0101 0011",
"S",
""
],
[
"84",
"0101 0100",
"T",
""
],
[
"85",
"0101 0101",
"U",
""
],
[
"86",
"0101 0110",
"V",
""
],
[
"87",
"0101 0111",
"W",
""
],
[
"88",
"0101 1000",
"X",
""
],
[
"89",
"0101 1001",
"Y",
""
],
[
"90",
"0101 1010",
"Z",
""
],
[
"91",
"0101 1011",
"[",
""
],
[
"92",
"0101 1100",
"\\",
""
],
[
"93",
"0101 1101",
"]",
""
],
[
"94",
"0101 1110",
"^",
""
],
[
"95",
"0101 1111",
"_",
""
],
[
"96",
"0110 0000",
"`",
""
],
[
"97",
"0110 0001",
"a",
""
],
[
"98",
"0110 0010",
"b",
""
],
[
"99",
"0110 0011",
"c",
""
],
[
"100",
"0110 0100",
"d",
""
],
[
"101",
"0110 0101",
"e",
""
],
[
"102",
"0110 0110",
"f",
""
],
[
"103",
"0110 0111",
"g",
""
],
[
"104",
"0110 1000",
"h",
""
],
[
"105",
"0110 1001",
"i",
""
],
[
"106",
"0110 1010",
"j",
""
],
[
"107",
"0110 1011",
"k",
""
],
[
"108",
"0110 1100",
"l",
""
],
[
"109",
"0110 1101",
"m",
""
],
[
"110",
"0110 1110",
"n",
""
],
[
"111",
"0110 1111",
"o",
""
],
[
"112",
"0111 0000",
"p",
""
],
[
"113",
"0111 0001",
"q",
""
],
[
"114",
"0111 0010",
"r",
""
],
[
"115",
"0111 0011",
"s",
""
],
[
"116",
"0111 0100",
"t",
""
],
[
"117",
"0111 0101",
"u",
""
],
[
"118",
"0111 0110",
"v",
""
],
[
"119",
"0111 0111",
"w",
""
],
[
"120",
"0111 1000",
"x",
""
],
[
"121",
"0111 1001",
"y",
""
],
[
"122",
"0111 1010",
"z",
""
],
[
"123",
"0111 1011",
"{",
""
],
[
"124",
"0111 1100",
"|",
""
],
[
"125",
"0111 1101",
"}",
""
],
[
"126",
"0111 1110",
"~",
""
],
[
"127",
"0111 1111",
"DEL",
""
]
],
"row_header": 0
}
],
"input_tables": []
}

View File

@@ -0,0 +1,68 @@
{
"schema_version": 2,
"title": "Sixteen-bit view of the code points in Hello算法",
"summary": "Align English and Chinese characters in the same string to 16 bits to compare the convenience and storage cost of fixed-width encoding.",
"context": [
"The two columns are headed \"Character\" and \"Unicode\", listing the 7-character string Hello算法 (without spaces) from top to bottom. The table below preserves the 16-bit binary values shown in the figure and adds the corresponding hexadecimal code points converted from binary."
],
"description": [
"In the first five rows, the upper 8 bits of each English character are padded with 00000000 in gray, while the lower 8 bits retain the original code point. The brace on the right reads \"One-byte English characters (high bits padded with 0)\", and the brace beside the last two rows, \"算\" and \"法\", reads \"Two-byte Chinese characters\"."
],
"frames": [
{
"id": "source-44",
"book_path": "chapter_data_structure/character_encoding.assets/unicode_hello_algo.png",
"title": "Sixteen-bit view of the code points in Hello算法",
"explanation": "If 1-byte English code points and 2-byte Chinese code points were mixed directly without padding, two consecutive bytes could be misparsed either as a single Chinese character or as two English letters. Zero-padding in the figure makes every character in this example occupy 2 bytes so the stream can be sliced at fixed intervals, at the cost of using twice as much space as ASCII for the five English letters."
}
],
"tables": [
{
"caption": "Per-character code points of Hello算法",
"headers": [
"Position and character",
"16-bit binary in figure",
"Hexadecimal code point (added)"
],
"row_header": 0,
"rows": [
[
"1: H",
"00000000 01001000",
"U+0048"
],
[
"2: e",
"00000000 01100101",
"U+0065"
],
[
"3: l",
"00000000 01101100",
"U+006C"
],
[
"4: l",
"00000000 01101100",
"U+006C"
],
[
"5: o",
"00000000 01101111",
"U+006F"
],
[
"6: 算",
"01111011 10010111",
"U+7B97"
],
[
"7: 法",
"01101100 11010101",
"U+6CD5"
]
]
}
],
"result": "This diagram only illustrates 16-bit values for characters within the Basic Multilingual Plane (BMP). Unicode itself defines code points up to U+10FFFF, which require 21 bits; the actual byte length depends on the encoding scheme such as UTF-8 or UTF-16, and not all Unicode characters occupy a fixed 2 bytes."
}

View File

@@ -0,0 +1,82 @@
{
"schema_version": 2,
"title": "UTF-8 encoding of Hello算法",
"summary": "Compare single-byte and three-byte encodings across seven characters, identifying leading bytes and continuation bytes.",
"context": [
"The input string is Hello算法 without spaces. The figure writes the code points of these 7 characters in 16 bits because all of them fall within U+FFFF; the full Unicode code point range extends up to U+10FFFF and requires 21 bits, so this example should not be generalized to mean that every code point fits in 16 bits."
],
"description": [],
"frames": [
{
"id": "source-45",
"book_path": "chapter_data_structure/character_encoding.assets/utf-8_hello_algo.png",
"title": "UTF-8 encoding of Hello算法",
"explanation": "Each English character uses the single-byte template 0xxxxxxx, placing its code point in the lower 7 bits. Both \"算\" and \"法\" use the three-byte template 1110xxxx 10xxxxxx 10xxxxxx: the leading byte starts with prefix 1110, where the 0 after the three 1s is also part of the prefix, and each of the two continuation bytes starts with 10. The remaining 4 + 6 + 6 payload bits hold the code point in order: \"算\" splits into 0111, 101110, and 010111, while \"法\" splits into 0110, 110011, and 010101."
}
],
"tables": [
{
"caption": "Per-character code points and UTF-8 bytes",
"headers": [
"Position and character",
"Unicode code point (from binary)",
"16-bit code point in figure",
"UTF-8 binary bytes",
"Byte count"
],
"rows": [
[
"1: H",
"U+0048",
"00000000 01001000",
"01001000",
"1"
],
[
"2: e",
"U+0065",
"00000000 01100101",
"01100101",
"1"
],
[
"3: l",
"U+006C",
"00000000 01101100",
"01101100",
"1"
],
[
"4: l",
"U+006C",
"00000000 01101100",
"01101100",
"1"
],
[
"5: o",
"U+006F",
"00000000 01101111",
"01101111",
"1"
],
[
"6: 算",
"U+7B97",
"01111011 10010111",
"11100111 10101110 10010111",
"3"
],
[
"7: 法",
"U+6CD5",
"01101100 11010101",
"11100110 10110011 10010101",
"3"
]
],
"row_header": 0
}
],
"result": "These bit prefixes distinguish single-byte characters, multi-byte leading bytes, and continuation bytes. In this example, the five English characters take 1 byte each and the two Chinese characters take 3 bytes each, for a total of 5 × 1 + 2 × 3 = 11 bytes."
}

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"title": "Logical relationships in data structures",
"summary": "Compare four kinds of logical relationships: sequential order, parent-child hierarchy, network connections, and key-value mapping.",
"context": [],
"description": [
"The left column of the figure groups linear data structures, and the right column groups nonlinear data structures; the hash table spans across the bottom beneath both columns to illustrate key-value mapping separately."
],
"frames": [
{
"id": "source-38",
"book_path": "chapter_data_structure/classification_of_data_structure.assets/classification_logic_structure.png",
"title": "Logical relationships in data structures",
"explanation": "Linear structures maintain a sequential order while differing in where operations are permitted; trees and heaps organize parent-child hierarchies, and graphs allow a vertex to connect to multiple neighbors. What is compared here is logical structure rather than underlying physical storage: the same logical relationship can be implemented in different ways, and a hash table can combine arrays, linked lists, or trees."
}
],
"tables": [
{
"caption": "Examples and connections for each data structure",
"headers": [
"Structure",
"Column in figure",
"Elements and relationships shown"
],
"rows": [
[
"Array",
"Linear",
"Arranged in order 1, 3, 2, 5, 4"
],
[
"Linked list",
"Linear",
"1→3→2→5→4"
],
[
"Stack",
"Linear",
"1, 3, 2, 5, 4 from the open end to the closed end; both push and pop occur at the open end"
],
[
"Queue",
"Linear",
"1, 3, 2, 5, 4 from the dequeue end to the enqueue end; push (enqueue) and pop (dequeue) occur at opposite ends"
],
[
"Tree",
"Nonlinear",
"Root 1 with left child 2 and right child 3; 2 has left 4 and right 5; 3 has left 6 and right 7; 7 nodes across three levels"
],
[
"Graph",
"Nonlinear",
"5 vertices 1 through 5; 7 undirected edges: 1—2, 1—3, 2—3, 2—4, 2—5, 3—5, 4—5"
],
[
"Heap",
"Nonlinear",
"Root 1 with left child 3 and right child 2; 3 has left 5 and right 4; 5 nodes across three levels"
],
[
"Hash table",
"Full-width row across both columns",
"Keys a, b, and c map to values 1, 2, and 3, respectively"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,62 @@
{
"schema_version": 2,
"title": "Storage layout of arrays and linked lists",
"summary": "The same logical sequence can be stored contiguously or linked via pointers across noncontiguous nodes.",
"context": [],
"description": [
"Both the left and right panels show schematic 5-by-6 memory grids, with rows numbered from top to bottom and columns from left to right, both starting at 1. On the left, the array stores 1, 3, 2, 5, 4 contiguously in the first 5 cells of row 2; on the right, linked list nodes are scattered across the grid, with each node occupying an adjacent value cell and pointer cell.",
"Light gray cells represent free memory; cells storing the array are green, while in the linked list, value cells are cyan and pointer cells are light blue. The table below lists each node's grid location in linked-list traversal order."
],
"frames": [
{
"id": "source-40",
"book_path": "chapter_data_structure/classification_of_data_structure.assets/classification_phisical_structure.png",
"title": "Storage layout of arrays and linked lists",
"explanation": "An array expresses sequential order through adjacent memory locations, whereas a linked list is traversed by following next pointers. Consequently, although node 4 lies in the top row, it still comes last in 1 → 3 → 2 → 5 → 4. The figure does not label its specific pointer value. Contiguous storage avoids storing an extra pointer per element; noncontiguous nodes can utilize fragmented free memory, at the cost of storing a pointer alongside each value."
}
],
"tables": [
{
"caption": "Schematic grid locations and successors of linked list nodes (1-based rows and columns)",
"headers": [
"Node value",
"Value cell",
"Pointer cell",
"Successor"
],
"rows": [
[
"1",
"Row 2, column 2",
"Row 2, column 3",
"3"
],
[
"3",
"Row 3, column 3",
"Row 3, column 4",
"2"
],
[
"2",
"Row 5, column 2",
"Row 5, column 3",
"5"
],
[
"5",
"Row 5, column 5",
"Row 5, column 6",
"4"
],
[
"4",
"Row 1, column 5",
"Row 1, column 6",
"No outgoing arrow drawn"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,44 @@
{
"schema_version": 2,
"title": "Accessing memory by address",
"summary": "Locate a memory cell by adding its row base address and column offset, then read the data stored there.",
"context": [],
"description": [
"On the left is a vertical memory module whose black chip area connects via two gray lines to the memory grid on the right. Those physical chips are not at the same level of representation as the dark cells indicating used memory inside the grid.",
"The grid shows 5 rows and 8 columns: row base addresses are 0x0000, 0x0010, 0x0020, 0x0030, and 0x0040, and column offsets run from 00 to 07; ellipses on the right and bottom indicate additional cells not drawn. Light cells represent free memory and dark cells represent used memory; free memory does not mean the cell contains the number 0."
],
"frames": [
{
"id": "source-39",
"book_path": "chapter_data_structure/classification_of_data_structure.assets/computer_memory_location.png",
"title": "Accessing memory by address",
"explanation": "Adding the row base address and column offset pinpoints a cell. For example, 0x0020 plus offset 04 gives 0x0024, yielding data value 2. The two read callouts below the grid correspond to the two rows in the table. An address identifies a location, whereas data is the content stored at that location; the grid is an addressing diagram rather than the physical circuit layout of a memory chip."
}
],
"tables": [
{
"caption": "Two used memory cells highlighted in the figure",
"headers": [
"Full address",
"Row base address",
"Column offset",
"Stored data"
],
"rows": [
[
"0x0012",
"0x0010",
"02",
"1"
],
[
"0x0024",
"0x0020",
"04",
"2"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,55 @@
{
"schema_version": 2,
"title": "Eight-bit sign-magnitude, one's complement, and two's complement",
"summary": "Compare how positive and negative integers convert across the three encodings, and see why two's complement has only one representation of zero.",
"context": [],
"description": [
"The figure arranges sign-magnitude, one's complement, and two's complement in three rows comparing +0, +5, −0, and −28, each written as 8 bits grouped into two 4-bit nibbles. Bidirectional arrows connect sign-magnitude with one's complement and one's complement with two's complement; the notes on the right state the forward rules for converting a negative number from sign-magnitude to one's complement and then to two's complement."
],
"frames": [
{
"id": "source-41",
"book_path": "chapter_data_structure/number_encoding.assets/1s_2s_complement.png",
"title": "Eight-bit sign-magnitude, one's complement, and two's complement",
"explanation": "The highest bit is the sign bit, and +0 and +5 have identical bit patterns across all three representations. For a negative number, keep the leading sign bit 1 and invert only the lower 7 bits to get the one's complement, then add 1 and keep the lower 8 bits to get the two's complement. In the table, −28 follows this rule; the reverse conversion subtracts 1 from the two's complement and then inverts the lower 7 bits while keeping the sign bit to return to sign-magnitude. Adding 1 to the one's complement of −0 (1111 1111) produces the nine-bit value 1 0000 0000; discarding the carry-out leaves 0000 0000, identical to +0, so positive zero and negative zero can no longer be distinguished from the two's complement."
}
],
"tables": [
{
"caption": "Eight-bit encoding comparison",
"headers": [
"Number",
"Sign-magnitude",
"One's complement",
"Two's complement"
],
"rows": [
[
"+0",
"0000 0000",
"0000 0000",
"0000 0000"
],
[
"+5",
"0000 0101",
"0000 0101",
"0000 0101"
],
[
"−0",
"1000 0000",
"1111 1111",
"0000 0000"
],
[
"−28",
"1001 1100",
"1110 0011",
"1110 0100"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,56 @@
{
"schema_version": 2,
"title": "Bit fields of a single-precision floating-point number",
"summary": "Split a 32-bit encoding into sign, exponent, and fraction fields, then evaluate the number it represents.",
"context": [
"This example shows a 4-byte IEEE 754 single-precision float. The 32 bit cells are arranged left to right from bit 31 down to bit 0, with brackets marking the orange sign bit S, the blue exponent E, and the green fraction N."
],
"description": [
"The table below lists each field and its stored bits first. Bit positions are indexed starting from bit 0 at the rightmost end; b31, b30, b23, b22, and b0 are labeled at the field boundaries in the figure."
],
"frames": [
{
"id": "source-42",
"book_path": "chapter_data_structure/number_encoding.assets/ieee_754_float.png",
"title": "Bit fields of a single-precision floating-point number",
"explanation": "Because E lies between 1 and 254, the normal-number formula applies: the sign factor is +1; the unbiased exponent is 124 − 127 = −3, so the scaling factor is 2 to the power of −3, which equals 0.125. In the fraction, only the 2nd and 3rd bits after the binary point are 1, giving N = 2 to the power of −2 + 2 to the power of −3 = 0.375; adding the implicit leading 1 yields 1.375. Multiplying all three factors gives 1 × 0.125 × 1.375 = 0.171875, matching the calculation at the bottom right of the figure."
}
],
"tables": [
{
"caption": "Fields in the 32-bit encoding and their meanings",
"headers": [
"Field",
"Bit range",
"Bit width",
"Binary in example",
"Interpretation"
],
"rows": [
[
"Sign bit S",
"Bit 31",
"1",
"0",
"Positive sign"
],
[
"Exponent E",
"Bits 30 to 23",
"8",
"01111100",
"Stored biased exponent is decimal 124"
],
[
"Fraction N",
"Bits 22 to 0",
"23",
"01100000000000000000000",
"First 3 bits are 011, remaining 20 bits are 0"
]
],
"row_header": 0
}
],
"result": "The normal-number formula is (−1)^S × 2^(E−127) × (1+N), that is, negative one to the power S, times 2 to the power (E minus 127), times (1 plus N). When E is 0 or 255, dedicated rules govern zero, subnormal numbers, infinity, and NaN, so this formula cannot be applied directly. The exponent widens the representable range without increasing significand precision: a normal float has 23 fraction bits plus the implicit 1, giving 24 bits of binary precision, so adjacent representable numbers generally grow farther apart as magnitude increases."
}

View File

@@ -0,0 +1,141 @@
{
"schema_version": 2,
"title": "Recursive binary search",
"summary": "Recursively search ten sorted elements for 6, shrinking the search interval from [0, 9] to [0, 3] and then [2, 3], finally returning index 2.",
"context": [
"The input consists of ten elements in increasing order at indices 0 through 9, with target 6; the full array is listed in the \"Fixed sorted input\" table. Here f(i, j) denotes searching the closed interval [i, j], with midpoint index m equal to floor((i + j) / 2)."
],
"description": [
"After comparing the midpoint value against the target at each step, recursion enters only the single subinterval that could still contain the target. Excluded positions remain in the original array; once the target is hit, its index is returned directly without any merge step. The two tables below list the full input and the three calls."
],
"frames": [
{
"id": "source-312",
"book_path": "chapter_divide_and_conquer/binary_search_recur.assets/binary_search_recur.png",
"title": "Recursive binary search",
"explanation": "The note at the bottom reads \"The final result is index 2 for element 6\". Counting by the closed intervals in the table, the number of candidates drops from 10 to 4 to 2, and the third call hits the target and returns immediately."
}
],
"animations": {
"flow-recursive-search": {
"kind": "prose",
"prose": {
"title": "Recursive binary search",
"summary": "Three states step through the three recursive calls in order, showing each call's current interval, midpoint, and next call or return value.",
"context": [
"The target value is 6 and the input array never changes, so element values can be looked up in the \"Fixed sorted input\" table above; the parameters of all three calls can also be looked up by call in the \"Three recursive calls\" table."
],
"description": [],
"steps": [
{
"id": "step-1",
"title": "Inspect midpoint value 12",
"explanation": "On the initial closed interval [0, 9], compute midpoint m = floor((0 + 9) / 2) = 4, where the element at index 4 is 12. Since 12 > 6, the target can only lie in the left half; exclude indices 4 through 9 and recursively call f(0, 3).",
"key_state": "f(0, 9): midpoint m = 4 (value 12 > 6), recurse into left subinterval f(0, 3).",
"announcement": "Call f(0, 9); midpoint m = 4 has value 12, which is greater than target 6, so exclude indices 4 through 9 and recurse into f(0, 3)."
},
{
"id": "step-2",
"title": "Inspect midpoint value 3",
"explanation": "On the closed interval [0, 3], compute midpoint m = floor((0 + 3) / 2) = 1, where the element at index 1 is 3. Since 3 < 6, the target can only lie in the right half; exclude indices 0 and 1 and recursively call f(2, 3).",
"key_state": "f(0, 3): midpoint m = 1 (value 3 < 6), recurse into right subinterval f(2, 3).",
"announcement": "Call f(0, 3); midpoint m = 1 has value 3, which is less than target 6, so exclude indices 0 and 1 and recurse into f(2, 3)."
},
{
"id": "step-3",
"title": "Hit target value 6",
"explanation": "On the closed interval [2, 3], compute midpoint m = floor((2 + 3) / 2) = 2, where the element at index 2 is 6, matching the target value; return index 2 directly up the call chain with no combine step needed.",
"key_state": "f(2, 3): midpoint m = 2 (value 6 = 6), target found and index 2 returned.",
"announcement": "Call f(2, 3); midpoint index 2 has value 6, hitting the target and returning index 2 directly."
}
]
}
}
},
"tables": [
{
"caption": "Fixed sorted input",
"headers": [
"Index",
"Value"
],
"rows": [
[
"0",
"1"
],
[
"1",
"3"
],
[
"2",
"6"
],
[
"3",
"8"
],
[
"4",
"12"
],
[
"5",
"15"
],
[
"6",
"23"
],
[
"7",
"26"
],
[
"8",
"31"
],
[
"9",
"35"
]
],
"row_header": 0
},
{
"caption": "Three recursive calls",
"headers": [
"Call (closed interval)",
"Midpoint index m",
"Midpoint value",
"Comparison",
"Next action"
],
"rows": [
[
"f(0, 9)",
"4",
"12",
"12 > 6",
"Recursive call f(0, 3)"
],
[
"f(0, 3)",
"1",
"3",
"3 < 6",
"Recursive call f(2, 3)"
],
[
"f(2, 3)",
"2",
"6",
"6 = 6",
"Return index 2"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,54 @@
{
"schema_version": 2,
"title": "Representing recursive tree-building index intervals with i, l, m, and r",
"summary": "The left subtree root is at preorder index i+1 and the right subtree root is at i+1+(m−l), where m−l is the number of nodes in the left subtree.",
"context": [
"The input consists of preorder traversal preorder = [3, 9, 2, 1, 7] and inorder traversal inorder = [9, 3, 1, 2, 7], with all node values distinct.",
"Array indices are 0-based: i is the index of the current subtree's root in preorder; [l, r] is the closed interval occupied by the current subtree in inorder; and m is the index of the current subtree's root in inorder. Note that m is obtained by looking up the root value in inorder (or via a hash table), not as the geometric midpoint of [l, r]."
],
"description": [
"The diagram labels the symbolic pointers for the top-level call. Reading 0-based indices from the positions shown: root 3 is at preorder index i = 0, the closed inorder interval is [l, r] = [0, 4], and the root's inorder index is m = 1. Hence the left subtree size is m − l = 1; these numeric indices are read off from cell positions, while the diagram primarily shows symbolic labels.",
"The left subtree's root immediately follows the current root at preorder index i + 1. The right subtree's root skips past the current root and all m − l left-subtree nodes, landing at preorder index i + 1 + (m − l).",
"The corresponding tree on the left has root 3 with left child 9 and right child 2; node 2 has left child 1 and right child 7, and 9, 1, and 7 are leaves. In the recursive implementation, whenever an empty inorder interval with l > r is reached, the call immediately returns an empty subtree. In the table below, i, l, m, and r in the formulas all refer to the current parent call, while the last column gives the concrete preorder root index and inorder interval for this example."
],
"frames": [
{
"id": "source-315",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/build_tree_division_pointers.png",
"title": "Representing recursive tree-building index intervals with i, l, m, and r",
"explanation": "Using the algebraic relationships among pointer variables i, l, m, and r, each recursive call can delimit the left and right subtrees accurately by passing integer indices alone, without slicing or copying subarrays."
}
],
"tables": [
{
"caption": "General formulas and example values for recursive parameters",
"headers": [
"Subproblem",
"Root index in preorder",
"Closed interval in inorder",
"This example"
],
"rows": [
[
"Current tree",
"i",
"[l,r]",
"Preorder root index 0, inorder interval [0,4], root value 3; root's inorder index m=1"
],
[
"Left subtree",
"i+1",
"[l,m−1]",
"Preorder root index 1, inorder interval [0,0], root value 9"
],
[
"Right subtree",
"i+1+(m−l)",
"[m+1,r]",
"Preorder root index 2, inorder interval [2,4], root value 2"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,22 @@
{
"schema_version": 2,
"title": "Reconstructing a five-node binary tree from preorder and inorder traversals",
"summary": "From preorder [3,9,2,1,7] and inorder [9,3,1,2,7], uniquely reconstruct the five-node binary tree rooted at 3.",
"context": [
"We are given a binary tree's preorder traversal sequence preorder = [3, 9, 2, 1, 7] and inorder traversal sequence inorder = [9, 3, 1, 2, 7], where all node values in the tree are distinct.",
"Preorder traversal visits nodes in \"root → left subtree → right subtree\" order, whereas inorder traversal visits them in \"left subtree → root → right subtree\" order. Together, their complementary positional structure uniquely determines the entire binary tree."
],
"description": [
"The left side of the figure shows the target binary tree to be reconstructed: root node 3 has left child 9 and right child 2; node 2 has left child 1 and right child 7; and nodes 9, 1, and 7 are leaf nodes.",
"The right side stacks the two traversal arrays vertically, with a leftward arrow labeled \"Reconstruct the binary tree\" pointing to the tree on the left. Checking against the traversal rules confirms why: the first preorder element, 3, identifies the overall root; in inorder, only 9 appears to the left of 3, so the left subtree contains node 9 alone; to the right of 3 lies [1, 2, 7], paired with the last three preorder elements [2, 1, 7], showing that the right subtree is rooted at 2 with left and right children 1 and 7.",
"Note that this is a general binary tree rather than a binary search tree: node placement is determined by traversal order and does not require a left child to be smaller than its parent (for example, left child 9 is greater than root 3)."
],
"frames": [
{
"id": "source-313",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/build_tree_example.png",
"title": "Reconstructing a five-node binary tree from preorder and inorder traversals",
"explanation": "Preorder pinpoints each subtree's root, while inorder partitions which nodes belong to its left and right subtrees; as long as all node values are distinct, the two sequences uniquely determine the tree."
}
]
}

View File

@@ -0,0 +1,90 @@
{
"schema_version": 2,
"title": "Using the root's inorder position to split left and right subtrees, then splitting preorder",
"summary": "The first preorder element, 3, identifies the root; inorder splits into left subtree [9] and right subtree [1,2,7], and those subtree sizes then split preorder.",
"context": [
"The input is preorder traversal preorder = [3, 9, 2, 1, 7] and inorder traversal inorder = [9, 3, 1, 2, 7], with all node values distinct."
],
"description": [
"Preorder visits the root first, so the first element of preorder, 3, is the root.",
"Locate 3 in inorder: to its left is only [9] and to its right is [1,2,7], telling us that the left and right subtrees contain 1 node and 3 nodes, respectively.",
"Split preorder accordingly: the single element [9] right after root 3 belongs to the left subtree, and the remaining [2,1,7] belongs to the right subtree. Both traversals of the right subtree contain the same set of nodes, visited in different orders.",
"On the left side of the figure, the entire five-node tree is also drawn for reference. Below, the first table lists the traversal slices produced by this split, and the second table lists all parent-child links in the tree."
],
"frames": [
{
"id": "source-314",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/build_tree_preorder_inorder_division.png",
"title": "Using the root's inorder position to split left and right subtrees, then splitting preorder",
"explanation": "This decomposes the original problem into two independent recursive subproblems for the left and right subtrees."
}
],
"tables": [
{
"caption": "Traversal sequences of the left and right subproblems",
"headers": [
"Part",
"Node count",
"Preorder",
"Inorder"
],
"rows": [
[
"Root",
"1",
"[3]",
"[3]"
],
[
"Left subtree",
"1",
"[9]",
"[9]"
],
[
"Right subtree",
"3",
"[2,1,7]",
"[1,2,7]"
]
],
"row_header": 0
},
{
"caption": "All parent-child links in the tree",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"9",
"2"
],
[
"9",
"None",
"None"
],
[
"2",
"1",
"7"
],
[
"1",
"None",
"None"
],
[
"7",
"None",
"None"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,443 @@
{
"schema_version": 2,
"title": "Recursive tree construction: create nodes on the way down, connect subtrees on return",
"summary": "Create nodes 3, 9, 2, 1, and 7 during recursive descent, and attach each subtree to its parent only as calls return, building the five-node tree.",
"context": [
"The input is preorder traversal preorder = [3, 9, 2, 1, 7] and inorder traversal inorder = [9, 3, 1, 2, 7], with all node values distinct.",
"Each recursive subproblem first initializes the current root node from the first element of its active preorder segment (creating the node during top-down descent), then partitions by the inorder root position and recursively builds the left and right subtrees; only after a child call returns its subtree root does the parent call assign it to the current root's left or right reference (establishing edges during bottom-up return). Calls on empty intervals return None immediately."
],
"description": [
"Nine frames capture the moments when a node is created or a completed subtree is attached; empty-interval calls returning None are not shown as separate frames. In each step, the \"Tree construction step N\" table lists every node created so far and its child references. \"Not yet connected\" means the corresponding subtree is still awaiting construction or return, whereas \"No child\" means the node has no child on that side."
],
"result": "The finished tree has preorder traversal [3, 9, 2, 1, 7] and inorder traversal [9, 3, 1, 2, 7], matching the input.",
"frames": [
{
"id": "source-317",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_step1.png",
"title": "Create root node 3",
"explanation": "Enter the top-level call with i = 0 and inorder interval [0, 4], creating root 3 from the first preorder element. Finding 3 at inorder index 1 splits out left subtree [9] and a right subtree with inorder [1, 2, 7] and preorder [2, 1, 7]. Only root 3 exists so far, with no parent-child edges; recursion next builds the left subtree.",
"key_state": "Root node 3 created; left and right subtrees not yet connected.",
"announcement": "Create root node 3, partitioning left subtree [9] and the three nodes of the right subtree.",
"state_tables": [
{
"caption": "Tree construction step 1: nodes and references after creating root node 3",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"Not yet connected",
"Not yet connected"
]
],
"row_header": 0
}
]
},
{
"id": "source-318",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_step2.png",
"title": "Create leaf node 9",
"explanation": "Enter the left subproblem with i = 1 and inorder interval [0, 0], creating node 9. Both of its left and right inorder subintervals are empty, so those empty-subtree calls return None, making 9 a leaf node. Because the call building node 9 has not yet returned it to root 3, there is still no edge between the two nodes.",
"key_state": "Leaf node 9 created, not yet connected to root node 3.",
"announcement": "Recurse into the left subproblem, create leaf node 9, and prepare to return up.",
"state_tables": [
{
"caption": "Tree construction step 2: nodes and references after creating leaf node 9",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"Not yet connected",
"Not yet connected"
],
[
"9",
"No child",
"No child"
]
],
"row_header": 0
}
]
},
{
"id": "source-319",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_step3.png",
"title": "Attach left subtree 9",
"explanation": "The call that built node 9 returns it to root 3, and the parent call sets 3.left = 9, establishing the first edge. Root 3's right subtree has not been built yet, so execution next enters the right subproblem.",
"key_state": "Edge 3.left = 9 established; right subtree of root 3 still to be built.",
"announcement": "Attach the returned leaf node 9 as the left child of root node 3.",
"state_tables": [
{
"caption": "Tree construction step 3: nodes and references after attaching left subtree 9",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"9",
"Not yet connected"
],
[
"9",
"No child",
"No child"
]
],
"row_header": 0
}
]
},
{
"id": "source-320",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_step4.png",
"title": "Create right-subtree root 2",
"explanation": "Enter the right subproblem with i = 2 and inorder interval [2, 4], creating node 2 from the first element of the active preorder segment [2, 1, 7]. Node 2 lies at inorder index m = 3, splitting its left subproblem [1] and right subproblem [7]. Edge 3.left = 9 remains unchanged; neither side of 2 is connected yet, and the call rooted at 2 has not yet returned to 3, so there is no edge between 3 and 2.",
"key_state": "Node 2 created with both subtrees pending; only 3.left = 9 is connected, and 2 is not yet attached to 3.",
"announcement": "Create right-subtree root node 2 and partition its left and right subproblems [1] and [7].",
"state_tables": [
{
"caption": "Tree construction step 4: nodes and references after creating right-subtree root 2",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"9",
"Not yet connected"
],
[
"9",
"No child",
"No child"
],
[
"2",
"Not yet connected",
"Not yet connected"
]
],
"row_header": 0
}
]
},
{
"id": "source-321",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_step5.png",
"title": "Create leaf node 1",
"explanation": "Enter node 2's left subproblem with i = 3 and inorder interval [2, 2], creating leaf node 1. Its left and right inorder subintervals are empty, and the call building node 1 has not yet returned it to node 2. Four nodes now exist, with only 3.left = 9 connected; 1 is not yet attached to 2, and 2 is not yet attached to 3.",
"key_state": "Leaf node 1 created; only 3.left = 9 is connected, with 1 not yet attached to 2 and 2 not yet attached to 3.",
"announcement": "Create leaf node 1 and prepare to return up to parent node 2.",
"state_tables": [
{
"caption": "Tree construction step 5: nodes and references after creating leaf node 1",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"9",
"Not yet connected"
],
[
"9",
"No child",
"No child"
],
[
"2",
"Not yet connected",
"Not yet connected"
],
[
"1",
"No child",
"No child"
]
],
"row_header": 0
}
]
},
{
"id": "source-322",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_step6.png",
"title": "Attach left subtree of node 2",
"explanation": "The call building node 1 returns to node 2, and the parent call sets 2.left = 1. Edges 3.left = 9 and 2.left = 1 are now in place; node 2's right subproblem [7] still awaits construction, and 2 has not yet returned to attach to 3.",
"key_state": "Edges 3.left = 9 and 2.left = 1 connected; 2.right still pending, and 2 not yet attached to 3.",
"announcement": "Attach the returned leaf node 1 as the left child of node 2.",
"state_tables": [
{
"caption": "Tree construction step 6: nodes and references after attaching the left subtree of node 2",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"9",
"Not yet connected"
],
[
"9",
"No child",
"No child"
],
[
"2",
"1",
"Not yet connected"
],
[
"1",
"No child",
"No child"
]
],
"row_header": 0
}
]
},
{
"id": "source-323",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_step7.png",
"title": "Create leaf node 7",
"explanation": "Enter node 2's right subproblem with i = 4 and inorder interval [4, 4], creating the final leaf node 7. All five nodes are now created; edges 3.left = 9 and 2.left = 1 exist, while 2.right and 3.right are still unconnected. The call building node 7 is about to return it to node 2.",
"key_state": "All five nodes created; 3.left = 9 and 2.left = 1 are connected, while 2.right and 3.right remain unconnected.",
"announcement": "Create leaf node 7 and prepare to return up to parent node 2.",
"state_tables": [
{
"caption": "Tree construction step 7: nodes and references after creating leaf node 7",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"9",
"Not yet connected"
],
[
"9",
"No child",
"No child"
],
[
"2",
"1",
"Not yet connected"
],
[
"1",
"No child",
"No child"
],
[
"7",
"No child",
"No child"
]
],
"row_header": 0
}
]
},
{
"id": "source-324",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_step8.png",
"title": "Attach right subtree of node 2",
"explanation": "The call building node 7 returns to node 2, and the parent call sets 2.right = 7. Three edges now exist: 3.left = 9, 2.left = 1, and 2.right = 7; the subtree rooted at 2 is complete and ready to return to root 3, though no edge connects 3 and 2 yet.",
"key_state": "Edge 3.left = 9 connected, and the subtree rooted at 2 (left 1, right 7) is complete; 2 is not yet attached to 3.",
"announcement": "Attach leaf node 7 as the right child of node 2, completing the subtree rooted at 2.",
"state_tables": [
{
"caption": "Tree construction step 8: nodes and references after attaching the right subtree of node 2",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"9",
"Not yet connected"
],
[
"9",
"No child",
"No child"
],
[
"2",
"1",
"7"
],
[
"1",
"No child",
"No child"
],
[
"7",
"No child",
"No child"
]
],
"row_header": 0
}
]
},
{
"id": "source-325",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_step9.png",
"title": "Attach complete right subtree",
"explanation": "The right subtree rooted at 2 returns to the top-level call, which sets 3.right = 2 to establish the final edge. Now 3 has left child 9 and right child 2, node 2 has left child 1 and right child 7, and 9, 1, and 7 are leaves. With all four parent-child edges established, the top-level call returns root 3, completing the reconstruction.",
"key_state": "Tree construction complete: 3 connects to left 9 and right 2, and 2 connects to left 1 and right 7.",
"announcement": "Attach the completed right subtree rooted at 2 to the right of root node 3, and return root 3 to finish.",
"state_tables": [
{
"caption": "Tree construction step 9: nodes and references after attaching the complete right subtree",
"headers": [
"Node",
"Left child",
"Right child"
],
"rows": [
[
"3",
"9",
"2"
],
[
"9",
"No child",
"No child"
],
[
"2",
"1",
"7"
],
[
"1",
"No child",
"No child"
],
[
"7",
"No child",
"No child"
]
],
"row_header": 0
}
]
}
],
"animations": {
"build-binary-tree": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-317"
},
{
"id": "step-2",
"frame_id": "source-318"
},
{
"id": "step-3",
"frame_id": "source-319"
},
{
"id": "step-4",
"frame_id": "source-320"
},
{
"id": "step-5",
"frame_id": "source-321"
},
{
"id": "step-6",
"frame_id": "source-322"
},
{
"id": "step-7",
"frame_id": "source-323"
},
{
"id": "step-8",
"frame_id": "source-324"
},
{
"id": "step-9",
"frame_id": "source-325"
}
]
}
},
"tables": [
{
"caption": "Fixed traversal input",
"headers": [
"Index",
"Preorder value",
"Inorder value"
],
"rows": [
[
"0",
"3",
"9"
],
[
"1",
"9",
"3"
],
[
"2",
"2",
"1"
],
[
"3",
"1",
"2"
],
[
"4",
"7",
"7"
]
],
"row_header": 0
}
],
"input_tables": [
0
]
}

View File

@@ -0,0 +1,66 @@
{
"schema_version": 2,
"title": "Inspecting the preorder and inorder partitions at each subproblem",
"summary": "Root 3 splits into left leaf 9 and the right subtree rooted at 2, and node 2 splits into left and right leaves 1 and 7; beside each node, its active traversal intervals are highlighted.",
"context": [
"The input is preorder traversal preorder = [3, 9, 2, 1, 7] and inorder traversal inorder = [9, 3, 1, 2, 7], with all node values distinct.",
"The reconstructed binary tree has root 3, left child 9, and right child 2; node 2 has left child 1 and right child 7; and nodes 9, 1, and 7 are leaf nodes."
],
"description": [
"Beside each of the five tree nodes, the diagram draws full-length copies of the preorder and inorder arrays, coloring only the interval belonging to that recursive subproblem while dimming unrelated positions in light gray. Within each subproblem, cyan marks the current subtree's root node, blue marks its left-subtree interval, and purple marks its right-subtree interval.",
"Light gray cells remain part of the original arrays and are simply outside the current subproblem; at a leaf node, the active slice contains only the root, with empty left and right subtree segments. The table below writes out the root, left segment, and right segment of each active sequence explicitly, with \"Left and right subtree roots\" summarized from the parent-child edges in the diagram."
],
"result": "Every subproblem applies the same rule: preorder identifies the root and inorder partitions the left and right ranges, while the empty intervals on both sides of each leaf return null references.",
"frames": [
{
"id": "source-316",
"book_path": "chapter_divide_and_conquer/build_binary_tree_problem.assets/built_tree_overall.png",
"title": "Inspecting the preorder and inorder partitions at each subproblem",
"explanation": "The same node value takes on different color roles in the arrays of different recursive subproblems: for instance, element 2 belongs to the purple right-subtree interval in the top-level arrays at root 3, whereas in the subproblem rooted at 2 itself it becomes the cyan root element. All five circular tree nodes themselves are drawn in green."
}
],
"tables": [
{
"caption": "Active sequences for each non-empty recursive subproblem",
"headers": [
"Current root",
"Active preorder parts: root, left, right",
"Active inorder parts: left, root, right",
"Left and right subtree roots"
],
"rows": [
[
"3",
"Root 3; left [9]; right [2, 1, 7]",
"Left [9]; root 3; right [1, 2, 7]",
"Left 9, right 2"
],
[
"9",
"Root 9; left empty; right empty",
"Left empty; root 9; right empty",
"Both empty"
],
[
"2",
"Root 2; left [1]; right [7]",
"Left [1]; root 2; right [7]",
"Left 1, right 7"
],
[
"1",
"Root 1; left empty; right empty",
"Left empty; root 1; right empty",
"Both empty"
],
[
"7",
"Root 7; left empty; right empty",
"Left empty; root 7; right empty",
"Both empty"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,21 @@
{
"schema_version": 2,
"title": "Splitting a bubble sort into two smaller sorting tasks",
"summary": "Compare sorting eight elements directly with bubble sort against splitting the array in half, bubble-sorting each half, and merging: both produce the same sorted result, and a single split remains quadratic.",
"context": [
"Both comparison paths share the input [7, 3, 2, 6, 0, 1, 5, 4] and the sorted target [0, 1, 2, 3, 4, 5, 6, 7]. Letting n denote the array length, the diagram compares operation counts before and after splitting via complexity expressions rather than measured runtimes."
],
"description": [
"The left path runs bubble sort directly on the full array of length n, labeled with time cost O(n²), and outputs the ascending array [0, 1, 2, 3, 4, 5, 6, 7] at the bottom.",
"The right path first splits the array at its midpoint into left half [7, 3, 2, 6] and right half [0, 1, 5, 4], labeled \"Divide O(n)\"; it then runs bubble sort on each subarray of length n/2, each labeled \"Bubble sort O((n/2)²)\", producing sorted left half [2, 3, 6, 7] and sorted right half [0, 1, 4, 5]; finally it performs \"Merge O(n)\", interleaving the smaller elements from both sides into [0, 1, 2, 3, 4, 5, 6, 7].",
"Crossing arrows in the merge stage on the right show that elements from the two sorted halves must be interleaved in value order rather than simply concatenated end to end. At the bottom, the total complexity of the right path is summarized as \"Overall: O(n²/2 + 2n)\", combining two half-size bubble sorts with linear dividing and merging."
],
"frames": [
{
"id": "source-310",
"book_path": "chapter_divide_and_conquer/divide_and_conquer.assets/divide_and_conquer_bubble_sort.png",
"title": "Splitting a bubble sort into two smaller sorting tasks",
"explanation": "After a single split, O(n²/2 + 2n) is still asymptotically O(n²). The simplified expression illustrates how reducing the coefficient on the quadratic term can lower work, rather than giving an exact operation count or guaranteeing that actual runtime is cut in half."
}
]
}

View File

@@ -0,0 +1,69 @@
{
"schema_version": 2,
"title": "Understanding divide and conquer through merge sort",
"summary": "Recursively split an eight-element sorting problem down to single-element base subproblems, then merge sorted results bottom-up into the ascending array from 0 to 7.",
"context": [
"The input array is [7, 3, 2, 6, 0, 1, 5, 4]; the upper half of the figure shows \"Divide (division phase)\" and the lower half shows \"Conquer (merge phase)\"."
],
"description": [
"Repeatedly split each subarray in half until every subproblem contains just one element. The left and right halves are disjoint and can be solved independently; a single element is already sorted without comparison.",
"While returning, merge each adjacent pair of sorted subarrays. At each step compare the frontmost remaining elements of the two halves and take the smaller one, appending any leftover elements once one half is exhausted. Merging level by level solves the full eight-element problem.",
"The upper half reaches eight singletons after three levels of splitting, and the lower half produces the sorted array after three levels of merging; the table below lists all seven rows of subarrays from top to bottom."
],
"frames": [
{
"id": "source-309",
"book_path": "chapter_divide_and_conquer/divide_and_conquer.assets/divide_and_conquer_merge_sort.png",
"title": "Understanding divide and conquer through merge sort",
"explanation": "Because each subproblem is still array sorting, the left and right subarrays are independent, and two sorted subarrays merge efficiently into one sorted array, merge sort exemplifies decomposability, subproblem independence, and combinable solutions in divide and conquer."
}
],
"tables": [
{
"caption": "Splitting and merging levels",
"headers": [
"Phase",
"Length per subarray",
"Subarrays (left to right)"
],
"rows": [
[
"Original problem",
"8",
"[7,3,2,6,0,1,5,4]"
],
[
"Split into two subproblems",
"4",
"[7, 3, 2, 6]; [0, 1, 5, 4]"
],
[
"Split further",
"2",
"[7, 3]; [2, 6]; [0, 1]; [5, 4]"
],
[
"Smallest subproblem",
"1",
"[7]; [3]; [2]; [6]; [0]; [1]; [5]; [4]"
],
[
"Merge into four sorted results",
"2",
"[3, 7]; [2, 6]; [0, 1]; [4, 5]"
],
[
"Merge into two sorted results",
"4",
"[2, 3, 6, 7]; [0, 1, 4, 5]"
],
[
"Merge into the solution to the original problem",
"8",
"[0,1,2,3,4,5,6,7]"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,21 @@
{
"schema_version": 2,
"title": "Parallel computation structure of bucket sort",
"summary": "Distribute unsorted data across six buckets, sort them in parallel on six processing units, and gather the buckets in order into sorted data.",
"context": [
"This structural diagram illustrates parallelizing divide and conquer without specifying concrete array values, bucket boundaries, or elapsed times. From top to bottom, it arranges \"Unsorted data\", six \"Bucket\" containers paired with six \"Processing unit\" blocks, and \"Sorted data\" at the bottom."
],
"description": [
"Six downward branching arrows distribute the unsorted data at the top into the six buckets; each bucket connects via a vertical dashed line to the processing unit below it, indicating that sorting within each bucket is independent and can be dispatched across separate processing units in parallel.",
"Once the six processing units finish sorting their respective buckets, output arrows converge on \"Sorted data\" at the bottom. When buckets partition the value range in ascending order, collecting the locally sorted buckets in bucket-range order concatenates them into a globally sorted result.",
"This figure illustrates how independent divide-and-conquer subproblems enable multicore or multiprocessor parallelism; because it omits per-bucket load balance and communication or merging overhead, six processing units in the diagram do not imply an automatic sixfold speedup."
],
"frames": [
{
"id": "source-311",
"book_path": "chapter_divide_and_conquer/divide_and_conquer.assets/divide_and_conquer_parallel_computing.png",
"title": "Parallel computation structure of bucket sort",
"explanation": "Divide and conquer decomposes the sorting task into non-overlapping per-bucket sorting subproblems that multiple processing units can execute in parallel before combining their solutions."
}
]
}

View File

@@ -0,0 +1,62 @@
{
"schema_version": 2,
"title": "Three-stage decomposition of the Tower of Hanoi",
"summary": "Break moving n disks from A to C into three ordered subproblems: n - 1 disks A → B, the largest disk A → C, and n - 1 disks B → C.",
"context": [
"The original problem f(n) moves n disks stacked from smallest on top to largest at the bottom from source rod A to destination rod C, illustrated here with five disks. Only one top disk may be moved at a time, and a larger disk may never sit on a smaller disk.",
"At the top level, A is the source rod, B is the auxiliary rod, and C is the destination rod; as recursion enters each subproblem, the three rods swap their source, auxiliary, and destination roles accordingly."
],
"description": [
"The left side summarizes moving all five disks from A to C, while the right side lists the three stages from top to bottom: first move the top n - 1 smaller disks from A to B using C; next move the largest disk from A to C as the single-disk subproblem f(1); finally move the n - 1 smaller disks from B onto the largest disk on C using A.",
"Both the first and third stages must still be recursively decomposed into legal single-disk moves rather than lifting a stack of smaller disks all at once. Dashed outlines mark positions before each stage and solid fills mark positions after it across the same five disks.",
"The table below lists for each stage the move task, auxiliary rod, and resulting disk configuration on rods A, B, and C."
],
"frames": [
{
"id": "source-327",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_divide_and_conquer.png",
"title": "Three-stage decomposition of the Tower of Hanoi",
"explanation": "These three sequentially dependent stages imply the move-count recurrence T(n) = 2T(n - 1) + 1 (not printed in the figure). Although the first and third subproblems have the same size, they assign different source, auxiliary, and destination rods."
}
],
"tables": [
{
"caption": "Three stages for the five-disk example",
"headers": [
"Stage",
"Move task",
"Auxiliary rod",
"Rod A after stage",
"Rod B after stage",
"Rod C after stage"
],
"rows": [
[
"Move smaller disks aside",
"Four smaller disks A → B",
"C",
"Largest disk",
"Four smaller disks",
"Empty"
],
[
"Move largest disk",
"Largest disk A → C",
"Not needed",
"Empty",
"Four smaller disks",
"Largest disk"
],
[
"Move smaller disks onto target",
"Four smaller disks B → C",
"A",
"Empty",
"Empty",
"All five disks stacked smallest on top to largest at bottom"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,20 @@
{
"schema_version": 2,
"title": "Tower of Hanoi example: moving six disks from A to C",
"summary": "Starting with six disks stacked from smallest on top to largest at the bottom on rod A, move them all to rod C using rod B while preserving their order.",
"context": [
"The Tower of Hanoi rules require moving only one disk at a time, taking it from the top of one rod and placing it onto the top of another, with smaller disks kept above larger disks at every step."
],
"description": [
"The upper half shows the starting state: three rods labeled A, B, and C from left to right, with six differently colored disks stacked from smallest at the top to largest at the bottom on rod A while rods B and C are empty.",
"The lower half shows the goal state: rods A and B are empty, and all six disks sit on rightmost rod C in their original order from smallest on top to largest at the bottom. A downward arrow in the middle labeled \"Move all disks from A to C\" summarizes the overall objective rather than implying the whole stack can be moved at once."
],
"frames": [
{
"id": "source-326",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_example.png",
"title": "Tower of Hanoi example: moving six disks from A to C",
"explanation": "This figure defines only the starting and goal states without expanding intermediate steps, which must be carried out as a sequence of legal single-disk moves."
}
]
}

View File

@@ -0,0 +1,44 @@
{
"schema_version": 2,
"title": "One-disk Tower of Hanoi (f(1))",
"summary": "Move the sole disk on rod A directly to destination rod C in a single move.",
"context": [
"The three rods from left to right are A, B, and C. Only one top disk may be moved at a time, and a larger disk may never sit on a smaller one. Subproblem f(1) moves a single disk and serves as the base case of the recursive decomposition."
],
"description": [
"A green rounded rectangle represents the sole disk. The two frames show the state before and after that single move."
],
"frames": [
{
"id": "source-329",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f1_step1.png",
"title": "Sole disk on rod A",
"explanation": "Initially A = [green disk], B = [], and C = [], with no move made yet. Because nothing blocks the disk and destination rod C is empty, it can move directly from A to C without using auxiliary rod B.",
"key_state": "Rod A holds one disk, rods B and C are empty, and no move has occurred yet.",
"announcement": "Show the initial state with the single disk on rod A."
},
{
"id": "source-330",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f1_step2.png",
"title": "Move the disk directly from rod A to rod C",
"explanation": "Because the sole green disk at the top of A is unobstructed and destination rod C is empty, move the disk directly from A to C without using B. Now A = [], B = [], and C = [green disk]; one single-disk move is complete, finishing the task.",
"key_state": "One single-disk move completed; the disk is on rod C, and rods A and B are empty.",
"announcement": "Move the sole disk directly from rod A to rod C."
}
],
"animations": {
"hanota-f1": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-329"
},
{
"id": "step-2",
"frame_id": "source-330"
}
]
}
}
}

View File

@@ -0,0 +1,69 @@
{
"schema_version": 2,
"title": "Moving two disks with auxiliary rod B",
"summary": "Park the small disk on rod B, move the large disk to rod C, and place the small disk onto the large disk in three moves total.",
"context": [
"The three rods from left to right are A, B, and C, and the goal is to move the two disks on A to C. Only one top disk may be moved at a time, and a larger disk cannot rest on a smaller disk; disk lists below are written from bottom to top on each rod.",
"Green denotes the large disk and blue denotes the small disk."
],
"description": [
"The four frames show the initial state followed by the states after each of the three single-disk moves: because step numbering in the player includes the initial frame, Steps 2, 3, and 4 complete moves 1, 2, and 3, respectively. Below the last three frames, completed move instructions are listed with the current move highlighted in light gray."
],
"frames": [
{
"id": "source-331",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f2_step1.png",
"title": "Two disks stacked on rod A",
"explanation": "Initially A = [large disk, small disk], B = [], and C = [], with no move made yet. Because the blue small disk rests above the green large disk, the small disk must move to auxiliary rod B before the large disk can be freed.",
"key_state": "No move yet; A holds the large disk then the small disk from bottom to top, and B and C are empty.",
"announcement": "Show the initial state with the large and small disks stacked on rod A."
},
{
"id": "source-332",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f2_step2.png",
"title": "Move the small disk from rod A to rod B first",
"explanation": "Move 1: move the blue small disk from A onto empty rod B, exposing the green large disk at the top of A. Now A = [large disk], B = [small disk], and C = [].",
"key_state": "Move 1 complete; A holds the large disk, B holds the small disk, and C is empty.",
"announcement": "Move 1: move the small disk from rod A to auxiliary rod B."
},
{
"id": "source-333",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f2_step3.png",
"title": "Next move the large disk from rod A to rod C",
"explanation": "Move 2: with the green large disk on A unobstructed and rod C empty, move the large disk from A to C. Now A = [], B = [small disk], and C = [large disk], with the small disk still waiting on B.",
"key_state": "Move 2 complete; A is empty, B holds the small disk, and C holds the large disk.",
"announcement": "Move 2: move the large disk from rod A to destination rod C."
},
{
"id": "source-334",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f2_step4.png",
"title": "Finally move the small disk from rod B to rod C",
"explanation": "Move 3: place the blue small disk from B onto the green large disk on C, keeping the smaller disk on top. Now A = [], B = [], and C = [large disk, small disk], completing the two-disk transfer.",
"key_state": "Move 3 complete; A and B are empty, and C holds the large disk then the small disk from bottom to top.",
"announcement": "Move 3: move the small disk from rod B onto the large disk on rod C, completing the transfer."
}
],
"animations": {
"hanota-f2": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-331"
},
{
"id": "step-2",
"frame_id": "source-332"
},
{
"id": "step-3",
"frame_id": "source-333"
},
{
"id": "step-4",
"frame_id": "source-334"
}
]
}
}
}

View File

@@ -0,0 +1,69 @@
{
"schema_version": 2,
"title": "Divide and conquer for the three-disk Tower of Hanoi",
"summary": "Transfer the top two disks to B, move the largest disk to C, and transfer the two disks from B to C across three stages totaling seven single-disk moves.",
"context": [
"The three rods from left to right are A, B, and C, and the goal is to move the three disks on A to C. Only one top disk may be moved at a time, and a larger disk cannot rest on a smaller disk; disk lists below are written from bottom to top on each rod.",
"Green denotes the large disk, blue the medium disk, and orange the small disk. A solid cyan outline groups the medium and small disks to represent the size-2 subproblem f(2), without implying both disks can be lifted together."
],
"description": [
"The four frames show the starting state and the end states of the three stages: each of the two f(2) stages takes three legal single-disk moves, plus one move of the large disk in between for seven moves in total. Player step numbers index frames rather than cumulative single-disk moves."
],
"frames": [
{
"id": "source-335",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f3_step1.png",
"title": "Group the top two disks as a subproblem",
"explanation": "Initially A = [large disk, medium disk, small disk], B = [], and C = [], with no move made yet. Freeing the bottom large disk requires moving the medium and small disks inside the cyan outline at the top of A to B first; within that f(2) subproblem, B is the destination rod and C is the auxiliary rod.",
"key_state": "No move yet; A holds the large, medium, and small disks from bottom to top, and B and C are empty.",
"announcement": "Treat the top two disks on rod A as a subproblem of size 2."
},
{
"id": "source-336",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f3_step2.png",
"title": "Complete the two-disk subproblem: A to B",
"explanation": "The first f(2) stage—with A as source rod, C as auxiliary rod, and B as destination rod—has completed: small disk A → C, medium disk A → B, and small disk C → B, for three cumulative single-disk moves. Now A = [large disk], B = [medium disk, small disk], and C = [], with the cyan outline moved onto B alongside the medium and small disks. The frame jumps directly to the stage outcome without expanding those three internal moves.",
"key_state": "Three cumulative single-disk moves; A holds the large disk, B holds the medium then small disk from bottom to top, and C is empty.",
"announcement": "Using rod C as auxiliary, transfer the top two disks from A to B in three single-disk moves."
},
{
"id": "source-337",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f3_step3.png",
"title": "Move the largest disk from A to C",
"explanation": "With the two smaller disks parked on B, the large disk on A is unobstructed and rod C is empty, so move the large disk from A to C. Now A = [], B = [medium disk, small disk], and C = [large disk], bringing the cumulative total to four single-disk moves while the cyan outline remains around the medium and small disks on B.",
"key_state": "Four cumulative single-disk moves; A is empty, B holds the medium then small disk from bottom to top, and C holds the large disk.",
"announcement": "Move the remaining largest disk directly from rod A to rod C."
},
{
"id": "source-338",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_f3_step4.png",
"title": "Complete the two-disk subproblem: B to C",
"explanation": "The second f(2) stage—with B as source rod, A as auxiliary rod, and C as destination rod—performs small disk B → A, medium disk B → C, and small disk A → C. Now A = [], B = [], and C = [large disk, medium disk, small disk], completing the transfer in seven cumulative single-disk moves with the cyan outline around the medium and small disks on C.",
"key_state": "Seven cumulative single-disk moves; A and B are empty, and C holds the large, medium, and small disks from bottom to top, completing the transfer.",
"announcement": "Using rod A as auxiliary, transfer the two disks on B to C in three more single-disk moves for seven moves in total, completing the transfer."
}
],
"animations": {
"hanota-f3": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-335"
},
{
"id": "step-2",
"frame_id": "source-336"
},
{
"id": "step-3",
"frame_id": "source-337"
},
{
"id": "step-4",
"frame_id": "source-338"
}
]
}
}
}

View File

@@ -0,0 +1,21 @@
{
"schema_version": 2,
"title": "Tower of Hanoi recursion tree: two smaller tasks plus one single-disk move",
"summary": "Every Tower of Hanoi problem larger than 1 splits into two smaller transfer tasks flanking one single-disk move until every task executes directly.",
"context": [
"Each node f(k) denotes the subproblem size of moving k disks. Every problem with k > 1 decomposes into moving the top k - 1 disks aside, moving the largest disk at the bottom, and moving the k - 1 disks onto the destination rod. Nodes in the figure label only subproblem sizes without writing each subproblem's distinct source, auxiliary, and destination rods."
],
"description": [
"At the top of the recursion tree sits the original problem f(n), branching downward from left to right into three children: f(n - 1), f(1), and f(n - 1). Each green f(n - 1) node on the left and right branches further into f(n - 2), f(1), and f(n - 2), whereas the middle cyan node f(1) is already a smallest single-move subproblem that does not split further.",
"Green boxes denote subproblems that still decompose recursively, while cyan boxes denote base-case single-disk moves f(1). Intermediate levels are condensed with ellipses \"…\", and the bottom row consists entirely of cyan f(1) nodes; because this diagram schematically represents general n, do not count the drawn cyan boxes as the exact move count for a specific n."
],
"result": "From this decomposition (formulas not printed in the figure), let T(n) be the number of disk moves. The base case is T(1) = 1. For n > 1, T(n) = 2T(n - 1) + 1, giving 2ⁿ − 1 (one less than 2 to the power n) total single-disk moves and O(2ⁿ) time complexity. Because the left and right branches execute sequentially and reuse stack space after returning, the longest active call chain along f(n) → f(n - 1) → … → f(1) holds n dfs stack frames, giving O(n) stack space counted by call depth.",
"frames": [
{
"id": "source-328",
"book_path": "chapter_divide_and_conquer/hanota_problem.assets/hanota_recursive_tree.png",
"title": "Tower of Hanoi recursion tree: two smaller tasks plus one single-disk move",
"explanation": "Strictly matching the chapter code, each middle cyan f(1) executes move directly inside its parent call without invoking dfs(1); only the left and right f(1) children of each f(2) run as actual dfs(1) calls. Thus the figure depicts a problem-decomposition tree rather than treating every box as a separate dfs call."
}
]
}

View File

@@ -0,0 +1,19 @@
{
"schema_version": 2,
"title": "Ways to reach step 3 when two consecutive 1-step moves are forbidden",
"summary": "Adding the constraint against two consecutive 1-step moves discards 0→1→2→3, leaving 2 valid ways to reach step 3.",
"context": [
"Starting from ground level 0, each move may still climb 1 or 2 steps toward target step 3, under the added constraint that two consecutive moves may not both climb 1 step."
],
"description": [
"The staircase labels steps 0 through 6 with target step 3 shaded green. Route 0→1→2→3 is drawn as a gray dotted curve with the callout above \"Because two consecutive one-step moves are forbidden, the route 0 → 1 → 2 → 3 is discarded\"; the solid blue curve 0→2→3 and solid orange curve 0→1→3 remain highlighted, and the bottom caption reads \"There are 2 ways to reach step 3: 0 → 2 → 3, 0 → 1 → 3\"."
],
"frames": [
{
"id": "source-374",
"book_path": "chapter_dynamic_programming/dp_problem_features.assets/climbing_stairs_constraint_example.png",
"title": "Ways to reach step 3 when two consecutive 1-step moves are forbidden",
"explanation": "Route 0→1→2→3 takes three consecutive 1-step moves, violating the ban on two consecutive 1-step moves in its very first two moves, so it is grayed out and discarded. Blue route 0→2→3 climbs 2 steps then 1 step, and orange route 0→1→3 climbs 1 step then 2 steps; neither contains adjacent 1-step moves, so both remain valid."
}
]
}

View File

@@ -0,0 +1,45 @@
{
"schema_version": 2,
"title": "Extending the dynamic programming state with the previous step size",
"summary": "Recording whether the last move climbed 1 or 2 steps in the two-dimensional state dp[i, j] excludes consecutive 1-step moves during transitions.",
"context": [
"Each move climbs 1 or 2 steps, with two consecutive 1-step moves forbidden. Because whether a 1-step move is currently allowed depends on the previous step size, extend the state to two-dimensional dp[i, j]: the number of ways to reach step i whose last move climbed j steps (for j = 1 or 2)."
],
"description": [
"On the top step, the figure labels two target states: cyan dp[i, 1] and blue dp[i, 2]; on step i - 1, cyan dp[i - 1, 2] and gray dp[i - 1, 1]; and on step i - 2, blue dp[i - 2, 1] and blue dp[i - 2, 2]. A solid cyan arc spans 1 step from dp[i - 1, 2] to dp[i, 1], whereas a gray dotted arc from gray dp[i - 1, 1] to dp[i, 1] carries the note \"Two consecutive one-step moves are forbidden, so this term is discarded\"; from dp[i - 2, 1] and dp[i - 2, 2], two solid blue arcs each span 2 steps into dp[i, 2].",
"When the final move climbs 1 step from step i - 1, the move that reached step i - 1 must have climbed 2 steps, giving dp[i, 1] = dp[i - 1, 2]. When the final move climbs 2 steps from step i - 2, the move that reached step i - 2 could have climbed either 1 or 2 steps, giving dp[i, 2] = dp[i - 2, 1] + dp[i - 2, 2].",
"The figure draws only symbolic transitions without numeric initial values. The table below supplies the initial states at steps 1 and 2 from the chapter code, from which recurrence begins at step 3."
],
"result": "Once the state includes the last move's step size, valid subsequent moves depend only on the current state, restoring the no-aftereffect property; the total number of ways to reach step n is dp[n, 1] + dp[n, 2].",
"frames": [
{
"id": "source-375",
"book_path": "chapter_dynamic_programming/dp_problem_features.assets/climbing_stairs_constraint_state_transfer.png",
"title": "Extending the dynamic programming state with the previous step size",
"explanation": "Step 1 has only 0→1, so dp[1, 1] = 1 and dp[1, 2] = 0. For step 2, 0→1→2 takes two consecutive 1-step moves and is invalid; only 0→2 is valid, so dp[2, 1] = 0 and dp[2, 2] = 1."
}
],
"tables": [
{
"caption": "Initial states in the chapter code (supplied base cases)",
"headers": [
"Step i",
"dp[i,1]",
"dp[i,2]"
],
"rows": [
[
"1",
"1",
"0"
],
[
"2",
"0",
"1"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,89 @@
{
"schema_version": 2,
"title": "State transitions for minimum climbing cost",
"summary": "Each state takes the smaller cumulative minimum cost of its two predecessors and adds cost[i], the cost of the current step.",
"context": [
"Each move climbs 1 or 2 steps, cost[i] is the nonnegative cost paid upon landing on step i, and starting on the ground is free. Let dp[i] denote the minimum cumulative cost to reach step i."
],
"description": [
"Green blocks dp[1] through dp[9] run horizontally from left to right; odd-indexed cost labels sit above and even-indexed ones sit below, pointing into their respective dp blocks. States dp[1] and dp[2] receive only their own cost arrows; starting at dp[3], brackets and min markers combine the two preceding states into the next state, with a plus sign beside the incoming cost arrow for paying the current step's cost. Below the diagram appear the initial states and general recurrence dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i] without concrete cost numbers.",
"The final move onto step i must come from either step i - 1 or step i - 2. Because landing on step i pays cost[i] regardless of predecessor, compare predecessor costs dp[i - 1] and dp[i - 2] to pick the smaller cumulative cost and then add cost[i].",
"From the ground one can step directly onto step 1 or step 2, giving dp[1] = cost[1]. Because cost[1] is nonnegative, passing through step 1 on the way to step 2 can never cost less than stepping straight onto step 2, so dp[2] = cost[2]. The table below lists steps 1 through 9 individually for lookup; the \"Ground\" origin and \"no worse than via step 1\" notes are supplied from the problem rules rather than a separate ground node drawn in the figure."
],
"frames": [
{
"id": "source-373",
"book_path": "chapter_dynamic_programming/dp_problem_features.assets/min_cost_cs_dp.png",
"title": "State transitions for minimum climbing cost",
"explanation": "Evaluating sequentially up to the target step yields the minimum cumulative cost in that step's dp entry."
}
],
"tables": [
{
"caption": "Initial values and predecessor comparisons",
"headers": [
"State",
"Initial source or compared predecessors",
"Cost paid at step",
"Formula"
],
"rows": [
[
"dp[1]",
"Ground",
"cost[1]",
"dp[1] = cost[1]"
],
[
"dp[2]",
"Two-step jump directly from ground (no worse than via step 1)",
"cost[2]",
"dp[2] = cost[2]"
],
[
"dp[3]",
"dp[2] or dp[1]",
"cost[3]",
"min(dp[2], dp[1]) + cost[3]"
],
[
"dp[4]",
"dp[3] or dp[2]",
"cost[4]",
"min(dp[3], dp[2]) + cost[4]"
],
[
"dp[5]",
"dp[4] or dp[3]",
"cost[5]",
"min(dp[4], dp[3]) + cost[5]"
],
[
"dp[6]",
"dp[5] or dp[4]",
"cost[6]",
"min(dp[5], dp[4]) + cost[6]"
],
[
"dp[7]",
"dp[6] or dp[5]",
"cost[7]",
"min(dp[6], dp[5]) + cost[7]"
],
[
"dp[8]",
"dp[7] or dp[6]",
"cost[8]",
"min(dp[7], dp[6]) + cost[8]"
],
[
"dp[9]",
"dp[8] or dp[7]",
"cost[9]",
"min(dp[8], dp[7]) + cost[9]"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,48 @@
{
"schema_version": 2,
"title": "Minimum cost to climb a three-step staircase",
"summary": "With costs 0, 1, 10, and 1 on the ground and steps 1 through 3, stepping over cost-10 step 2 along 0→1→3 achieves the minimum total cost of 2.",
"context": [
"Each move climbs 1 or 2 steps and pays the cost of every step landed on; the figure labels step numbers as n and step costs as cost[n]. Ground start has cost[0] = 0, and the goal is to land on step 3 and pay step 3's cost."
],
"description": [
"Aligned beneath the staircase are step numbers n = 0, 1, 2, 3 and costs cost[n] = 0, 1, 10, 1, with step 2's tread and cost 10 highlighted in red and target step 3's tread highlighted in green. Above the steps, a solid cyan curve traces 0→1→2→3, a blue dotted curve traces 0→2→3, and an orange dashed curve traces 0→1→3. The bottom note states that among these 3 routes, 0→1→3 has the minimum cost of 2.",
"Single-step costs in the table below come from cost in the figure, while the sums and totals 12 and 11 are computed by adding the steps visited rather than printed in the figure."
],
"frames": [
{
"id": "source-372",
"book_path": "chapter_dynamic_programming/dp_problem_features.assets/min_cost_cs_example.png",
"title": "Minimum cost to climb a three-step staircase",
"explanation": "Both of the first two routes land on step 2 of cost 10; only 0→1→3 steps over it, achieving the lowest total cost."
}
],
"tables": [
{
"caption": "Costs of the three routes (computed from cost in the figure)",
"headers": [
"Route",
"Cost calculation",
"Total cost"
],
"rows": [
[
"0→1→2→3",
"1+10+1",
"12"
],
[
"0→2→3",
"10+1",
"11"
],
[
"0→1→3",
"1+1",
"2"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,115 @@
{
"schema_version": 2,
"title": "Redundant recursion in minimum path sum",
"summary": "When looking up predecessors from dp[2, 1], two call paths each reach dp[1, 0] and expand its subtree once, making the second expansion redundant.",
"context": [
"Moving only right or down from [0, 0] in a nonnegative grid, dp[i, j] denotes the minimum path sum to row i, column j (zero-based). Rooted at dp[2, 1], this figure shows the top-down brute-force recursion tree without concrete grid weights; note that recursion looks backward to the \"Previous row\" and \"Previous column\" predecessors, opposite to walking down and right.",
"Each valid interior state takes the smaller return value of its two predecessors plus the current cell's cost: dp[i, j] = min(dp[i - 1, j], dp[i, j - 1]) + grid[i, j]. Start [0, 0] returns grid[0, 0], and negative out-of-bounds indices return positive infinity."
],
"description": [
"In the recursion tree, the left branch queries the previous row (written \"Up\" in path notation) and the right branch queries the previous column (written \"Left\"); these direction words refer to predecessor directions in the grid rather than left/right positions in the tree drawing.",
"From root dp[2, 1] through dp[1, 1] to dp[1, 0] is path \"Up → Left\", while through dp[2, 0] to dp[1, 0] is path \"Left → Up\". This illustrates the bottom-right callout \"Source of overlapping subproblems: both dp[i+1, j] and dp[i, j+1] depend on dp[i, j]\": here both dp[2, 0] and dp[1, 1] depend on dp[1, 0].",
"Because brute-force search does not save solved states, both occurrences of dp[1, 0] expand children dp[0, 0] and dp[1, -1]. Negative-index nodes carry \"Prune: index out of bounds\" and return positive infinity in the code, excluding invalid predecessors during minimum comparisons.",
"Below, a 4×4 symbolic dp table (rows and columns 0 to 3) shades the six valid states involved in this search—[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], and [2, 1]—while leaving the other ten cells unshaded with their dp symbols. The table below lists the entire recursion tree in preorder (node, then Up, then Left), distinguishing repeated states by call path."
],
"frames": [
{
"id": "source-380",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dfs.png",
"title": "Two call paths expand subproblem dp[1, 0] twice",
"explanation": "Counted across the table, there are 13 call nodes in total: start state dp[0, 0] appears 3 times, and negative-index nodes appear 4 times—dp[-1, 1] once, dp[1, -1] twice, and dp[2, -1] once."
}
],
"tables": [
{
"caption": "Complete recursion tree; paths start at the root, and Up/Left denote predecessor lookups",
"headers": [
"Call path",
"State",
"Action or return",
"Child nodes"
],
"rows": [
[
"Root",
"dp[2,1]",
"Take min of two predecessors, plus grid[2, 1]",
"Up: dp[1, 1]; Left: dp[2, 0]"
],
[
"Up",
"dp[1,1]",
"Take min of two predecessors, plus grid[1, 1]",
"Up: dp[0, 1]; Left: dp[1, 0]"
],
[
"Up → Up",
"dp[0,1]",
"Take min of two predecessors, plus grid[0, 1]",
"Up: dp[-1, 1]; Left: dp[0, 0]"
],
[
"Up → Up → Up",
"dp[-1,1]",
"Out of bounds, return +∞",
"Not expanded"
],
[
"Up → Up → Left",
"dp[0,0]",
"Start cell, return grid[0, 0]",
"Not expanded"
],
[
"Up → Left",
"dp[1,0]",
"Take min of two predecessors, plus grid[1, 0]",
"Up: dp[0, 0]; Left: dp[1, -1]"
],
[
"Up → Left → Up",
"dp[0,0]",
"Start cell, return grid[0, 0]",
"Not expanded"
],
[
"Up → Left → Left",
"dp[1,-1]",
"Out of bounds, return +∞",
"Not expanded"
],
[
"Left",
"dp[2,0]",
"Take min of two predecessors, plus grid[2, 0]",
"Up: dp[1, 0]; Left: dp[2, -1]"
],
[
"Left → Up",
"dp[1,0]",
"Take min of two predecessors, plus grid[1, 0]",
"Up: dp[0, 0]; Left: dp[1, -1]"
],
[
"Left → Up → Up",
"dp[0,0]",
"Start cell, return grid[0, 0]",
"Not expanded"
],
[
"Left → Up → Left",
"dp[1,-1]",
"Out of bounds, return +∞",
"Not expanded"
],
[
"Left → Left",
"dp[2,-1]",
"Out of bounds, return +∞",
"Not expanded"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,103 @@
{
"schema_version": 2,
"title": "Memoized recursion for minimum path sum",
"summary": "On the second request for dp[1, 0], return the cached valid path sum directly without expanding its children, distinct from returning positive infinity out of bounds.",
"context": [
"Moving only right or down from [0, 0] in a nonnegative grid, dp[i, j] denotes the minimum path sum to row i, column j (zero-based). Also rooted at dp[2, 1], this figure shows how adding memoization table mem prunes overlapping subproblems without concrete grid weights. Recursion looks backward to the previous row and previous column, opposite to walking down and right.",
"Each valid interior state takes the smaller return value of its two predecessors plus the current cell's cost: dp[i, j] = min(dp[i - 1, j], dp[i, j - 1]) + grid[i, j]. Start [0, 0] returns grid[0, 0], and negative out-of-bounds indices return positive infinity."
],
"description": [
"In the recursion tree, the left branch queries the previous row (written \"Up\" in path notation) and the right branch queries the previous column (written \"Left\"); these direction words refer to predecessor directions in the grid rather than left/right positions in the tree drawing.",
"From root dp[2, 1] through dp[1, 1] to dp[1, 0] is path \"Up → Left\", and through dp[2, 0] to dp[1, 0] is path \"Left → Up\". Both paths request the same subproblem.",
"Solving the dp[1, 1] branch first: on the first visit to dp[1, 0], wait for both predecessor calls to return, compute the cell's minimum path sum, store it in mem[1][0], and return to dp[1, 1]. When solving the dp[2, 0] branch afterward, requesting dp[1, 0] again hits \"Prune: result already cached\" and returns the cached value directly without calling dp[0, 0] or dp[1, -1]. The other child of dp[2, 0], dp[2, -1] (path \"Left → Left\"), is out of bounds and returns positive infinity, whereas the cached value is a valid finite path sum participating in the minimum.",
"This search touches six valid states across rows 0 to 2 and columns 0 to 1: [0, 0], [0, 1], [1, 0], [1, 1], [2, 0], and [2, 1]. Both dp[0, 1] and the first evaluation of dp[1, 0] call start state dp[0, 0] once along paths \"Up → Up → Left\" and \"Up → Left → Up\". Because [0, 0] immediately returns grid[0, 0] without reading or writing mem, both start leaves remain in the tree. The table below lists every call in preorder (node, then Up, then Left); this figure omits a separate grid or dp table."
],
"frames": [
{
"id": "source-381",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dfs_mem.png",
"title": "Cache hit reuses dp[1, 0] directly, distinct from out-of-bounds pruning",
"explanation": "Skipping the two children under the second dp[1, 0] reduces total call nodes from 13 in the brute-force tree to 11. Counted across the table, 2 start nodes dp[0, 0] and 3 out-of-bounds nodes—dp[-1, 1], dp[1, -1], and dp[2, -1]—remain."
}
],
"tables": [
{
"caption": "Complete recursion tree; paths start at the root, and Up/Left denote predecessor lookups",
"headers": [
"Call path",
"State",
"Action or return",
"Child nodes"
],
"rows": [
[
"Root",
"dp[2,1]",
"Take min of two predecessors, add grid[2, 1], and store in mem",
"Up: dp[1, 1]; Left: dp[2, 0]"
],
[
"Up",
"dp[1,1]",
"Take min of two predecessors, add grid[1, 1], and store in mem",
"Up: dp[0, 1]; Left: dp[1, 0]"
],
[
"Up → Up",
"dp[0,1]",
"Take min of two predecessors, add grid[0, 1], and store in mem",
"Up: dp[-1, 1]; Left: dp[0, 0]"
],
[
"Up → Up → Up",
"dp[-1,1]",
"Out of bounds, return +∞",
"Not expanded"
],
[
"Up → Up → Left",
"dp[0,0]",
"Start cell, return grid[0, 0]",
"Not expanded"
],
[
"Up → Left",
"dp[1,0]",
"Take min of two predecessors, add grid[1, 0], and store in mem",
"Up: dp[0, 0]; Left: dp[1, -1]"
],
[
"Up → Left → Up",
"dp[0,0]",
"Start cell, return grid[0, 0]",
"Not expanded"
],
[
"Up → Left → Left",
"dp[1,-1]",
"Out of bounds, return +∞",
"Not expanded"
],
[
"Left",
"dp[2,0]",
"Take min of two predecessors, add grid[2, 0], and store in mem",
"Up: dp[1, 0]; Left: dp[2, -1]"
],
[
"Left → Up",
"dp[1,0]",
"Cache hit, return solved dp[1, 0]",
"Not expanded"
],
[
"Left → Left",
"dp[2,-1]",
"Out of bounds, return +∞",
"Not expanded"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,728 @@
{
"schema_version": 2,
"title": "Dynamic programming for minimum path sum",
"summary": "Starting at the top-left cell, accumulate the costs along the unique boundary paths along the first row and first column, then fill interior cells row by row by adding the current cell cost to the minimum of the cell above and the cell to the left until reaching the bottom-right corner.",
"context": [
"Given the 4×4 nonnegative integer cost grid (zero-based row and column indices; full values in the input table), move from top-left start [0, 0] to bottom-right end [3, 3] stepping only one cell right or down at a time, counting both start and end cell values in the path sum.",
"Entry dp[i, j] stores the minimum path sum from start [0, 0] to row i, column j. Zeros filled into the table upon creation are merely uncomputed initial placeholders and never represent zero-cost paths."
],
"description": [
"Boundary initialization: set start dp[0, 0] = grid[0, 0] = 1; row 0 can only be reached by moving right from the left, and column 0 can only be reached by moving down from above, so accumulating along the first row and first column settles 7 valid boundary cells in total.",
"Interior recurrence: across the 9 interior cells in rows 1 to 3 and columns 1 to 3, evaluate dp[i, j] = min(dp[i - 1, j], dp[i, j - 1]) + grid[i, j] row by row from left to right so both dp[i - 1, j] above and dp[i, j - 1] to the left already hold valid results whenever needed. Each frame's state table pairs every cell's value with \"uncomputed initial value\", \"valid boundary\", or \"computed\" for direct lookup by coordinates."
],
"tables": [
{
"caption": "Dynamic programming process: input grid (zero-based row and column indices)",
"headers": [
"Row index",
"Column 0",
"Column 1",
"Column 2",
"Column 3"
],
"rows": [
[
"0",
"1",
"3",
"1",
"5"
],
[
"1",
"2",
"2",
"4",
"2"
],
[
"2",
"5",
"3",
"2",
"1"
],
[
"3",
"4",
"3",
"5",
"2"
]
],
"row_header": 0
}
],
"frames": [
{
"id": "source-382",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step1.png",
"title": "Initialize the dp table",
"explanation": "Create a 4×4 dp state table filled entirely with uncomputed initial values of 0; all 16 cells—including start [0, 0], row 0, and column 0—are still unevaluated, and 0 does not denote a zero-cost path.",
"key_state": "All 16 cells hold uncomputed initial values of 0; start and boundaries are not yet evaluated.",
"announcement": "Create the 4×4 dp table with all 16 cells initialized to uncomputed placeholder 0.",
"state_tables": [
{
"caption": "Minimum path sum step 1: dp state after initializing the dp table",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"1",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"2",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"3",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-383",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step2.png",
"title": "Compute first-row and first-column boundaries",
"explanation": "Start cell dp[0, 0] = grid[0, 0] = 1; accumulating rightward along row 0 gives [1, 4, 5, 10], and accumulating downward along column 0 gives [1, 3, 8, 12]. Seven boundary cells now hold valid boundary values, while the remaining 9 interior cells (rows 1 to 3, columns 1 to 3) still hold uncomputed initial values of 0.",
"key_state": "First row [1, 4, 5, 10] and first column [1, 3, 8, 12] give 7 valid boundary cells; the 9 interior cells remain uncomputed initial values of 0.",
"announcement": "Finish accumulating the start, first row [1, 4, 5, 10], and first column [1, 3, 8, 12] for 7 valid boundary cells; 9 interior cells remain uncomputed initial values of 0.",
"state_tables": [
{
"caption": "Minimum path sum step 2: dp state after computing first-row and first-column boundaries",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"2",
"8, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"3",
"12, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-384",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step3.png",
"title": "Compute dp[1, 1]",
"explanation": "Enter interior row 1, column 1: upper predecessor dp[0, 1] = 4 and left predecessor dp[1, 0] = 3; take the smaller value 3 plus current cell cost grid[1, 1] = 2 to get dp[1, 1] = min(4, 3) + 2 = 5. The remaining 8 interior cells ([1, 2], [1, 3], and rows 2 to 3, columns 1 to 3) still hold uncomputed initial values of 0.",
"key_state": "Computed dp[1, 1] = min(4, 3) + 2 = 5; the remaining 8 interior cells still hold uncomputed initial values of 0.",
"announcement": "Compare upper sum 4 with left sum 3 and add cell cost 2 to get dp[1, 1] = 5.",
"state_tables": [
{
"caption": "Minimum path sum step 3: dp state after computing dp[1, 1]",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"2",
"8, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"3",
"12, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-385",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step4.png",
"title": "Compute dp[1, 2]",
"explanation": "At [1, 2]: upper predecessor dp[0, 2] = 5 and left predecessor dp[1, 1] = 5 are equal; take either 5 plus current cell cost grid[1, 2] = 4 to get dp[1, 2] = min(5, 5) + 4 = 9. The remaining 7 interior cells ([1, 3] and rows 2 to 3, columns 1 to 3) still hold uncomputed initial values of 0.",
"key_state": "Computed dp[1, 2] = min(5, 5) + 4 = 9; the remaining 7 interior cells still hold uncomputed initial values of 0.",
"announcement": "Upper sum 5 equals left sum 5; add cell cost 4 to get dp[1, 2] = 9.",
"state_tables": [
{
"caption": "Minimum path sum step 4: dp state after computing dp[1, 2]",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"9, computed",
"0, uncomputed initial value"
],
[
"2",
"8, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"3",
"12, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-386",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step5.png",
"title": "Compute dp[1, 3]",
"explanation": "At the end of row 1, [1, 3]: upper predecessor dp[0, 3] = 10 and left predecessor dp[1, 2] = 9; take the smaller value 9 plus current cell cost grid[1, 3] = 2 to get dp[1, 3] = min(10, 9) + 2 = 11. Row 1 is now completely settled; the 6 interior cells in rows 2 to 3, columns 1 to 3 still hold uncomputed initial values of 0.",
"key_state": "Computed dp[1, 3] = min(10, 9) + 2 = 11; rows 0 and 1 plus the first-column boundary are complete, leaving 6 interior cells in rows 2 and 3 uncomputed.",
"announcement": "Compare upper sum 10 with left sum 9 and add cell cost 2 to get dp[1, 3] = 11.",
"state_tables": [
{
"caption": "Minimum path sum step 5: dp state after computing dp[1, 3]",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"9, computed",
"11, computed"
],
[
"2",
"8, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"3",
"12, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-387",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step6.png",
"title": "Compute dp[2, 1]",
"explanation": "Advance to the first interior cell of row 2, [2, 1]: upper predecessor dp[1, 1] = 5 and left predecessor dp[2, 0] = 8; take the smaller value 5 plus current cell cost grid[2, 1] = 3 to get dp[2, 1] = min(5, 8) + 3 = 8. The remaining 5 interior cells ([2, 2], [2, 3], and columns 1 to 3 of row 3) still hold uncomputed initial values of 0.",
"key_state": "Computed dp[2, 1] = min(5, 8) + 3 = 8; the remaining 5 interior cells still hold uncomputed initial values of 0.",
"announcement": "Compare upper sum 5 with left sum 8 and add cell cost 3 to get dp[2, 1] = 8.",
"state_tables": [
{
"caption": "Minimum path sum step 6: dp state after computing dp[2, 1]",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"9, computed",
"11, computed"
],
[
"2",
"8, valid boundary",
"8, computed",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"3",
"12, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-388",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step7.png",
"title": "Compute dp[2, 2]",
"explanation": "At [2, 2]: upper predecessor dp[1, 2] = 9 and left predecessor dp[2, 1] = 8; take the smaller value 8 plus current cell cost grid[2, 2] = 2 to get dp[2, 2] = min(9, 8) + 2 = 10. The remaining 4 interior cells ([2, 3], [3, 1], [3, 2], [3, 3]) still hold uncomputed initial values of 0.",
"key_state": "Computed dp[2, 2] = min(9, 8) + 2 = 10; the remaining 4 interior cells still hold uncomputed initial values of 0.",
"announcement": "Compare upper sum 9 with left sum 8 and add cell cost 2 to get dp[2, 2] = 10.",
"state_tables": [
{
"caption": "Minimum path sum step 7: dp state after computing dp[2, 2]",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"9, computed",
"11, computed"
],
[
"2",
"8, valid boundary",
"8, computed",
"10, computed",
"0, uncomputed initial value"
],
[
"3",
"12, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-389",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step8.png",
"title": "Compute dp[2, 3]",
"explanation": "At the end of row 2, [2, 3]: upper predecessor dp[1, 3] = 11 and left predecessor dp[2, 2] = 10; take the smaller value 10 plus current cell cost grid[2, 3] = 1 to get dp[2, 3] = min(11, 10) + 1 = 11. Row 2 is now completely settled; only [3, 1], [3, 2], and [3, 3] in row 3 hold uncomputed initial values of 0.",
"key_state": "Computed dp[2, 3] = min(11, 10) + 1 = 11; rows 0 through 2 plus the first-column boundary are complete, leaving 3 interior cells in row 3 uncomputed.",
"announcement": "Compare upper sum 11 with left sum 10 and add cell cost 1 to get dp[2, 3] = 11.",
"state_tables": [
{
"caption": "Minimum path sum step 8: dp state after computing dp[2, 3]",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"9, computed",
"11, computed"
],
[
"2",
"8, valid boundary",
"8, computed",
"10, computed",
"11, computed"
],
[
"3",
"12, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-390",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step9.png",
"title": "Compute dp[3, 1]",
"explanation": "Advance to [3, 1] in the bottom row: upper predecessor dp[2, 1] = 8 and left predecessor dp[3, 0] = 12; take the smaller value 8 plus current cell cost grid[3, 1] = 3 to get dp[3, 1] = min(8, 12) + 3 = 11. Only [3, 2] and destination [3, 3] remain at uncomputed initial value 0.",
"key_state": "Computed dp[3, 1] = min(8, 12) + 3 = 11; only [3, 2] and [3, 3] remain uncomputed.",
"announcement": "Compare upper sum 8 with left sum 12 and add cell cost 3 to get dp[3, 1] = 11.",
"state_tables": [
{
"caption": "Minimum path sum step 9: dp state after computing dp[3, 1]",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"9, computed",
"11, computed"
],
[
"2",
"8, valid boundary",
"8, computed",
"10, computed",
"11, computed"
],
[
"3",
"12, valid boundary",
"11, computed",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-391",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step10.png",
"title": "Compute dp[3, 2]",
"explanation": "At [3, 2]: upper predecessor dp[2, 2] = 10 and left predecessor dp[3, 1] = 11; take the smaller value 10 plus current cell cost grid[3, 2] = 5 to get dp[3, 2] = min(10, 11) + 5 = 15. Fifteen cells are now valid, leaving only destination dp[3, 3] at 0 (uncomputed initial value).",
"key_state": "Computed dp[3, 2] = min(10, 11) + 5 = 15; only destination dp[3, 3] remains at 0 (uncomputed initial value).",
"announcement": "Compare upper sum 10 with left sum 11 and add cell cost 5 to get dp[3, 2] = 15.",
"state_tables": [
{
"caption": "Minimum path sum step 10: dp state after computing dp[3, 2]",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"9, computed",
"11, computed"
],
[
"2",
"8, valid boundary",
"8, computed",
"10, computed",
"11, computed"
],
[
"3",
"12, valid boundary",
"11, computed",
"15, computed",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-392",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step11.png",
"title": "Compute dp[3, 3]",
"explanation": "Compute the final interior cell (destination) [3, 3]: upper predecessor dp[2, 3] = 11 and left predecessor dp[3, 2] = 15; take the smaller value 11 plus current cell cost grid[3, 3] = 2 to get dp[3, 3] = min(11, 15) + 2 = 13. All 16 cells in the table are now valid.",
"key_state": "Computed destination dp[3, 3] = min(11, 15) + 2 = 13; all 16 cells in the table are now valid.",
"announcement": "Compare upper sum 11 with left sum 15 and add destination cost 2 to get dp[3, 3] = 13.",
"state_tables": [
{
"caption": "Minimum path sum step 11: dp state after computing dp[3, 3]",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"9, computed",
"11, computed"
],
[
"2",
"8, valid boundary",
"8, computed",
"10, computed",
"11, computed"
],
[
"3",
"12, valid boundary",
"11, computed",
"15, computed",
"13, computed"
]
],
"row_header": 0
}
]
},
{
"id": "source-393",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_dp_step12.png",
"title": "Return the minimum path sum",
"explanation": "With all 16 state cells computed, this step performs no new calculation and simply reads and returns bottom-right destination dp[3, 3] = 13 as the minimum path sum. The procedure returns only the minimum cumulative cost without backtracking to output path coordinates.",
"key_state": "Table computation complete; return bottom-right destination minimum path sum dp[3, 3] = 13.",
"announcement": "Table recurrence complete; return destination minimum path sum 13.",
"state_tables": [
{
"caption": "Minimum path sum step 12: dp state when returning the minimum path sum",
"headers": [
"Row index i",
"Column j=0",
"Column j=1",
"Column j=2",
"Column j=3"
],
"rows": [
[
"0",
"1, valid boundary",
"4, valid boundary",
"5, valid boundary",
"10, valid boundary"
],
[
"1",
"3, valid boundary",
"5, computed",
"9, computed",
"11, computed"
],
[
"2",
"8, valid boundary",
"8, computed",
"10, computed",
"11, computed"
],
[
"3",
"12, valid boundary",
"11, computed",
"15, computed",
"13, computed"
]
],
"row_header": 0
}
]
}
],
"animations": {
"min-path-sum-dp": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-382"
},
{
"id": "step-2",
"frame_id": "source-383"
},
{
"id": "step-3",
"frame_id": "source-384"
},
{
"id": "step-4",
"frame_id": "source-385"
},
{
"id": "step-5",
"frame_id": "source-386"
},
{
"id": "step-6",
"frame_id": "source-387"
},
{
"id": "step-7",
"frame_id": "source-388"
},
{
"id": "step-8",
"frame_id": "source-389"
},
{
"id": "step-9",
"frame_id": "source-390"
},
{
"id": "step-10",
"frame_id": "source-391"
},
{
"id": "step-11",
"frame_id": "source-392"
},
{
"id": "step-12",
"frame_id": "source-393"
}
]
}
},
"input_tables": [
0
]
}

View File

@@ -0,0 +1,62 @@
{
"schema_version": 2,
"title": "Minimum path sum in a 4×4 grid",
"summary": "Moving only right or down from top left to bottom right in a 4×4 cost grid, the seven-cell green optimal path sums to 13.",
"context": [
"Given a 4×4 nonnegative integer grid where each cell value is the cost of passing through that cell, start at top-left [0, 0] and step one cell right or down at a time to reach bottom-right [3, 3], counting both start and end values in the path sum (zero-based row and column indices)."
],
"description": [
"The left panel shows the full 4×4 input grid with \"Start\" at the top left and \"End\" at the bottom right; a central rightward arrow points to the same 4×4 grid on the right with a seven-cell path from top left to bottom right highlighted in green, captioned below \"The minimum path sum is 13; the corresponding optimal path is 1 → 2 → 2 → 3 → 2 → 1 → 2\"."
],
"frames": [
{
"id": "source-376",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_example.png",
"title": "Minimum path sum in a 4×4 grid",
"explanation": "Starting at [0, 0] (value 1), the green optimal path on the right moves down to [1, 0] (value 2), right to [1, 1] (value 2), down to [2, 1] (value 3), right twice through [2, 2] (value 2) and [2, 3] (value 1), and finally down to end [3, 3] (value 2), summing to 1 + 2 + 2 + 3 + 2 + 1 + 2 = 13."
}
],
"tables": [
{
"caption": "Optimal path example: input grid (zero-based row and column indices)",
"headers": [
"Row index",
"Column 0",
"Column 1",
"Column 2",
"Column 3"
],
"rows": [
[
"0",
"1",
"3",
"1",
"5"
],
[
"1",
"2",
"2",
"4",
"2"
],
[
"2",
"5",
"3",
"2",
"1"
],
[
"3",
"4",
"3",
"5",
"2"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,58 @@
{
"schema_version": 2,
"title": "Boundary conditions and evaluation order for minimum path sum",
"summary": "Initialize the start cell and accumulate rightward along row 0 and downward along column 0 first, then traverse interior cells in forward order from top to bottom and left to right.",
"context": [
"Moving only right or down from [0, 0] in a nonnegative grid with both endpoints counted, dp[i, j] denotes the minimum path sum to row i, column j (indices 0 to 3). Using two 4×4 symbolic dp tables side by side, this figure illustrates \"Boundary conditions: initialize the first row and column\" and \"State transition order: traverse the matrix in forward order\" without concrete grid values."
],
"description": [
"On the left, green marks the top-left start cell, blue marks the rest of the first row, and purple marks the rest of the first column, with arrows running rightward across row 0 and downward along column 0. On the right, arrows show each interior cell depending on the already computed states above and to its left. Both tables display only symbolic labels dp[0, 0] through dp[3, 3].",
"First initialize the start cell, then accumulate along the unique incoming direction across the first row and first column. Fill the nine interior cells in forward order with outer row loop i = 1, 2, 3 and inner column loop j = 1, 2, 3, guaranteeing that when evaluating dp[i, j], upper dp[i - 1, j] was already computed in the previous row and left dp[i, j - 1] was already computed earlier in the current row. Formulas in the table below summarize these boundary and predecessor relationships and are not written cell by cell in the figure."
],
"frames": [
{
"id": "source-379",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_solution_initial_state.png",
"title": "Initialize first-row and first-column boundaries before row-major forward traversal",
"explanation": "Except for the starting cell, each cell in the first row or first column has only one valid predecessor; only interior cells take the minimum across both upper and left predecessors."
}
],
"tables": [
{
"caption": "Initialization and interior recurrence in the 4×4 symbolic table",
"headers": [
"Region",
"Index range",
"Predecessors",
"Computation"
],
"rows": [
[
"Start cell",
"[0,0]",
"None",
"dp[0,0]=grid[0,0]"
],
[
"First row",
"[0, j], j = 1, 2, 3",
"[0,j-1]",
"dp[0,j]=dp[0,j-1]+grid[0,j]"
],
[
"First column",
"[i, 0], i = 1, 2, 3",
"[i-1,0]",
"dp[i,0]=dp[i-1,0]+grid[i,0]"
],
[
"Interior",
"i = 1, 2, 3; j = 1, 2, 3 in each row",
"[i - 1, j] and [i, j - 1]",
"dp[i,j]=min(dp[i-1,j],dp[i,j-1])+grid[i,j]"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,64 @@
{
"schema_version": 2,
"title": "Defining grid coordinates as two-dimensional dp states",
"summary": "Define each state by row and column coordinates [i, j] and build a matching 4×4 two-dimensional dp table for the minimum path sum subproblems from the start to every cell.",
"context": [
"Given the 4×4 nonnegative cost grid (full values for indices 0 to 3 in the table) where a path starts at top-left [0, 0], moves one cell right or down at a time, and includes the cost of both endpoints, this figure contrasts the original grid with the state definition of the dp table."
],
"description": [
"First distinguish the meanings of the two 4×4 matrices: grid[i, j] records only the single-cell cost of stepping onto cell [i, j], whereas dp[i, j] records the cumulative minimum path sum from top-left start [0, 0] to [i, j] (inclusive). For example, grid[1, 1] = 2 is only that cell's own cost and must not be confused with cumulative path sum dp[1, 1], which also includes the path cost of reaching [1, 1] from the start.",
"Beside grid, row indices i, i + 1 and column indices j, j + 1 illustrate the per-step move decision from current cell [1, 1] (cost 2): moving one cell right increments the column index by 1 to [1, 2] ([i, j + 1], cost 4), and moving one cell down increments the row index by 1 to [2, 1] ([i + 1, j], cost 3). Because each move changes either the row or column coordinate by 1, two-dimensional indices [i, j] define the state.",
"On the right, the dp table is a 4×4 matrix of the same dimensions as grid (rows and columns 0 to 3), with cells labeled dp[0, 0] through dp[3, 3] representing the minimum path sum subproblem to each cell. This figure establishes only the state definition and coordinate mapping without yet computing numeric path sums."
],
"frames": [
{
"id": "source-377",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_solution_state_definition.png",
"title": "Correspondence between single-cell costs in grid and cumulative states dp[i, j]",
"explanation": "At the bottom, four modeling elements are summarized in order: the decision at each step moves one cell right or down; the state is the current cell's row and column indices [i, j]; the subproblem is the minimum path sum from top-left [0, 0] to [i, j]; and the dp table is the two-dimensional matrix storing all subproblem solutions."
}
],
"tables": [
{
"caption": "State definition: input grid (zero-based row and column indices)",
"headers": [
"Row index",
"Column 0",
"Column 1",
"Column 2",
"Column 3"
],
"rows": [
[
"0",
"1",
"3",
"1",
"5"
],
[
"1",
"2",
"2",
"4",
"2"
],
[
"2",
"5",
"3",
"2",
"1"
],
[
"3",
"4",
"3",
"5",
"2"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,63 @@
{
"schema_version": 2,
"title": "State transition for minimum path sum",
"summary": "Because the final step into an interior cell can come only from above or from the left, take the smaller of those two cumulative minimum path sums plus the current cell's cost.",
"context": [
"Moving only one cell right or down at a time from top-left [0, 0] in a nonnegative grid and summing all visited cells (including start and end), let dp[i, j] denote the minimum path sum to row i, column j (zero-based); the 4×4 input grid for this example appears in the table."
],
"description": [
"On the left is the 4×4 cost grid, and on the right is a symbolic dp table of equal size labeled dp[0, 0] through dp[3, 3]. In the left grid, current cell [2, 2] (value 2) is shaded green, upper neighbor [1, 2] (value 4) is shaded purple, and left neighbor [2, 1] (value 3) is shaded blue; the right table highlights dp[2, 2], dp[1, 2], and dp[2, 1] in matching colors.",
"In the right table, a downward arrow points from dp[1, 2] to dp[2, 2] and a rightward arrow points from dp[2, 1] to dp[2, 2]. Below appears the state transition equation dp[i, j] = min(dp[i - 1, j], dp[i, j - 1]) + grid[i, j]; note that min compares the cumulative minimum path sums to the two predecessor cells rather than the single-cell costs 4 and 3 in the left grid."
],
"frames": [
{
"id": "source-378",
"book_path": "chapter_dynamic_programming/dp_solution_pipeline.assets/min_path_sum_solution_state_transition.png",
"title": "State transition for minimum path sum",
"explanation": "For the green interior cell i = 2, j = 2, one can arrive only by stepping down from [1, 2] above or stepping right from [2, 1] on the left, giving dp[2, 2] = min(dp[1, 2], dp[2, 1]) + grid[2, 2] with grid[2, 2] = 2. The dp table on the right shows only symbolic dependencies here without filling in numeric cumulative sums."
}
],
"tables": [
{
"caption": "State transition: input grid (zero-based row and column indices)",
"headers": [
"Row index",
"Column 0",
"Column 1",
"Column 2",
"Column 3"
],
"rows": [
[
"0",
"1",
"3",
"1",
"5"
],
[
"1",
"2",
"2",
"4",
"2"
],
[
"2",
"5",
"3",
"2",
"1"
],
[
"3",
"4",
"3",
"5",
"2"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,48 @@
{
"schema_version": 2,
"title": "Decision tree for edit distance",
"summary": "Modeling strings as nodes and single edits as directed edges frames the problem as finding the shortest path from hello to algo in a decision tree; the figure expands one three-step transformation path while leaving other branches unexpanded.",
"context": [
"In the decision tree model, each node represents a string state, and each outgoing directed edge represents one decision (a single insertion, deletion, or replacement operation). Finding the edit distance from string s = hello to t = algo is equivalent to finding the shortest path from the root node hello to the target node algo in this decision tree."
],
"description": [
"From top to bottom on the left, the figure expands a single path of 4 string nodes and 3 directed edges, starting from s = hello at the top and ending at t = algo at the bottom. The table below lists each edge and its operation in order; the first edge in the drawing reads only \"Replace l with g,\" and \"the second l\" is added by comparing the two node strings to clarify the position.",
"To the right of each expanded node in the top three levels (hello, helgo, and halgo), 3 additional branch arrows point to ellipses \"...\", indicating that without restrictions on edits, every string can branch into many other edit choices; those abbreviated branches omit specific strings, since the figure illustrates the shortest-path perspective on the decision tree rather than exhausting the entire search tree."
],
"frames": [
{
"id": "source-442",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_decision_tree.png",
"title": "Three-step edit path from hello to algo",
"explanation": "This path reaches algo from hello in 3 edits, matching the edit distance of 3 shown in Figure 14-27 earlier in this section. Examining this single expanded path only confirms that 3 edits suffice; by itself, it cannot rule out a shorter path."
}
],
"tables": [
{
"caption": "Edits along the expanded path",
"headers": [
"Starting string",
"Operation",
"Resulting string"
],
"rows": [
[
"hello",
"Replace the second l with g",
"helgo"
],
[
"helgo",
"Replace e with a",
"halgo"
],
[
"halgo",
"Delete the leading h",
"algo"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,922 @@
{
"schema_version": 2,
"title": "Dynamic programming for edit distance",
"summary": "Fill the table cell by cell across source and target prefixes to find the minimum number of edits needed to transform string bag into pack.",
"context": [
"The source string s is bag (length 3), and the target string t is pack (length 4); note that this input differs from the other examples in the text. Each operation inserts, deletes, or replaces a single character at a cost of 1.",
"State dp[i, j] represents the minimum number of edits needed to transform the first i characters of source string s (the source prefix) into the first j characters of target string t (the target prefix). The two-dimensional table has 4 rows and 5 columns: rows i = 0 to 3 correspond to source prefixes empty string, b, ba, and bag; columns j = 0 to 4 correspond to target prefixes empty string, p, pa, pac, and pack."
],
"description": [
"First create a 4×5 all-zero table, in which dp[0, 0] is already the valid boundary value 0 for transforming one empty string into another; then initialize the positive-length entries in the first row as dp[0, j] = j (inserting j characters into the empty string to form the target prefix) and in the first column as dp[i, 0] = i (deleting i characters from the source prefix to reach the empty string). The remaining 12 interior cells are solved row by row from top to bottom, and from left to right within each row.",
"To compute dp[i, j], compare the final character s[i - 1] of the current source prefix with the final character t[j - 1] of the target prefix: if the two final characters match, no additional edit is needed, so the entry equals the upper-left value dp[i - 1, j - 1] directly (without adding 1); if they differ, take the minimum of the left entry dp[i, j - 1] (insertion), the upper entry dp[i - 1, j] (deletion), and the upper-left entry dp[i - 1, j - 1] (replacement), plus 1. Each step provides a uniquely named full state table marking every cell's value together with \"valid boundary,\" \"computed,\" or \"uncomputed initial value\"; step 15 marks the bottom-right cell as \"return value.\" Row and column headers give both i or j and the corresponding prefix for lookup either by coordinates or by prefix."
],
"frames": [
{
"id": "source-444",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step1.png",
"title": "Create the initial 4×5 all-zero dp table",
"explanation": "For source string s = bag (length 3) and target string t = pack (length 4), create a 4×5 two-dimensional dp table. All 20 cells currently hold 0: dp[0, 0] is already the valid boundary for transforming an empty string into an empty string, while the remaining 19 cells hold uncomputed initial values, with the positive-length boundaries in the first row and first column yet to be set.",
"key_state": "Initial 4×5 all-zero table (bag to pack): dp[0, 0] is already the valid boundary 0, and the other 19 cells hold uncomputed initial values awaiting positive-length boundary setup in the first row and first column.",
"announcement": "Create a 4×5 all-zero table for transforming bag into pack; the empty-to-empty boundary is 0, and the remaining boundaries are yet to be set.",
"state_tables": [
{
"caption": "Edit distance, step 1: full all-zero dp table",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=1, b",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=2, ba",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=3, bag",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-445",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step2.png",
"title": "Initialize the empty-string boundaries in the first row and first column",
"explanation": "Keep dp[0, 0] = 0 for transforming an empty string into an empty string. Initialize the first row from dp[0, 0] to dp[0, 4] as [0, 1, 2, 3, 4] (transforming the empty source prefix into the length-j target prefixes empty string, p, pa, pac, and pack requires inserting j characters, with dp[0, 4] = 4 for empty string to pack); initialize the first column from dp[0, 0] to dp[3, 0] as [0, 1, 2, 3] (transforming the length-i source prefixes empty string, b, ba, and bag into the empty string requires deleting i characters, with dp[3, 0] = 3 for bag to empty string). In the interior, across rows 1 to 3 and columns 1 to 4, the 12 entries of 0 remain uncomputed initial values.",
"key_state": "Empty-string boundaries set: first row [0, 1, 2, 3, 4] (dp[0, 4] = 4), first column [0, 1, 2, 3] (dp[3, 0] = 3).",
"announcement": "Initialize the first-row insertion boundary from the empty string as [0, 1, 2, 3, 4] and the first-column deletion boundary to the empty string as [0, 1, 2, 3].",
"state_tables": [
{
"caption": "Edit distance, step 2: full dp table after initializing empty-string boundaries",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=2, ba",
"2, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=3, bag",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-446",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step3.png",
"title": "Compute dp[1, 1] (source prefix b to target prefix p): minimum 1 edit",
"explanation": "At i = 1, j = 1, compute dp[1, 1] for transforming source prefix b into target prefix p: the source final character b and target final character p differ, so compare left dp[1, 0] = 1, above dp[0, 1] = 1, and upper-left dp[0, 0] = 0, take the minimum 0 plus 1 (corresponding to replacing b with p), and write dp[1, 1] = 1.",
"key_state": "dp[1, 1] (source prefix b to target prefix p, final characters b and p differ): min(left 1, above 1, upper-left 0) + 1 = 1.",
"announcement": "Compute dp[1, 1] (b to p): final characters b and p differ, so take the three-way minimum 0 plus 1 to get 1.",
"state_tables": [
{
"caption": "Edit distance, step 3: full dp table after computing dp[1, 1]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=2, ba",
"2, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=3, bag",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-447",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step4.png",
"title": "Compute dp[1, 2] (source prefix b to target prefix pa): minimum 2 edits",
"explanation": "At i = 1, j = 2, compute dp[1, 2] for transforming source prefix b into target prefix pa: the source final character b and target final character a differ, so compare left dp[1, 1] = 1, above dp[0, 2] = 2, and upper-left dp[0, 1] = 1, take the minimum 1 plus 1, and write dp[1, 2] = 2.",
"key_state": "dp[1, 2] (source prefix b to target prefix pa, final characters b and a differ): min(left 1, above 2, upper-left 1) + 1 = 2.",
"announcement": "Compute dp[1, 2] (b to pa): final characters b and a differ, so take the three-way minimum 1 plus 1 to get 2.",
"state_tables": [
{
"caption": "Edit distance, step 4: full dp table after computing dp[1, 2]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=2, ba",
"2, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=3, bag",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-448",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step5.png",
"title": "Compute dp[1, 3] (source prefix b to target prefix pac): minimum 3 edits",
"explanation": "At i = 1, j = 3, compute dp[1, 3] for transforming source prefix b into target prefix pac: the source final character b and target final character c differ, so compare left dp[1, 2] = 2, above dp[0, 3] = 3, and upper-left dp[0, 2] = 2, take the minimum 2 plus 1, and write dp[1, 3] = 3.",
"key_state": "dp[1, 3] (source prefix b to target prefix pac, final characters b and c differ): min(left 2, above 3, upper-left 2) + 1 = 3.",
"announcement": "Compute dp[1, 3] (b to pac): final characters b and c differ, so take the three-way minimum 2 plus 1 to get 3.",
"state_tables": [
{
"caption": "Edit distance, step 5: full dp table after computing dp[1, 3]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"0, uncomputed initial value"
],
[
"i=2, ba",
"2, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=3, bag",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-449",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step6.png",
"title": "Compute dp[1, 4] (source prefix b to target string pack): minimum 4 edits",
"explanation": "At i = 1, j = 4, compute dp[1, 4] for transforming source prefix b into the full target string pack: the source final character b and target final character k differ, so compare left dp[1, 3] = 3, above dp[0, 4] = 4, and upper-left dp[0, 3] = 3, take the minimum 3 plus 1, and write dp[1, 4] = 4, completing row 1.",
"key_state": "dp[1, 4] (source prefix b to target string pack, final characters b and k differ): min(left 3, above 4, upper-left 3) + 1 = 4, completing row 1.",
"announcement": "Compute dp[1, 4] (b to pack): final characters b and k differ, so take the three-way minimum 3 plus 1 to get 4, completing row 1.",
"state_tables": [
{
"caption": "Edit distance, step 6: full dp table after computing dp[1, 4]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=3, bag",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-450",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step7.png",
"title": "Compute dp[2, 1] (source prefix ba to target prefix p): minimum 2 edits",
"explanation": "Move to row 2 and process i = 2, j = 1 to compute dp[2, 1] for transforming source prefix ba into target prefix p: the source final character a and target final character p differ, so compare left dp[2, 0] = 2, above dp[1, 1] = 1, and upper-left dp[1, 0] = 1, take the minimum 1 plus 1, and write dp[2, 1] = 2.",
"key_state": "dp[2, 1] (source prefix ba to target prefix p, final characters a and p differ): min(left 2, above 1, upper-left 1) + 1 = 2.",
"announcement": "Move to row 2 and compute dp[2, 1] (ba to p): final characters a and p differ, so take the three-way minimum 1 plus 1 to get 2.",
"state_tables": [
{
"caption": "Edit distance, step 7: full dp table after computing dp[2, 1]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"2, computed",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=3, bag",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-451",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step8.png",
"title": "Compute dp[2, 2] (source prefix ba to target prefix pa): both end in a, take 1 directly",
"explanation": "At i = 2, j = 2, compute dp[2, 2] for transforming source prefix ba into target prefix pa: the current source prefix final character s[1] and target prefix final character t[1] are both a, so the two final characters match completely and need no additional edit; instead of adding 1 to the result for b to p, copy upper-left dp[1, 1] = 1 directly and write dp[2, 2] = 1.",
"key_state": "dp[2, 2] (source prefix ba to target prefix pa, both ending in a): no additional edit needed; take upper-left dp[1, 1] = 1 directly.",
"announcement": "Compute dp[2, 2] (ba to pa): both end in a, requiring no additional edit, so copy upper-left dp[1, 1] = 1 directly.",
"state_tables": [
{
"caption": "Edit distance, step 8: full dp table after computing dp[2, 2]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"2, computed",
"1, computed",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i=3, bag",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-452",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step9.png",
"title": "Compute dp[2, 3] (source prefix ba to target prefix pac): minimum 2 edits",
"explanation": "At i = 2, j = 3, compute dp[2, 3] for transforming source prefix ba into target prefix pac: the source final character a and target final character c differ, so compare left dp[2, 2] = 1, above dp[1, 3] = 3, and upper-left dp[1, 2] = 2, take the minimum from the left, 1 (inserting c on top of the 1-edit transformation from ba to pa), plus 1, and write dp[2, 3] = 2.",
"key_state": "dp[2, 3] (source prefix ba to target prefix pac, final characters a and c differ): min(left 1, above 3, upper-left 2) + 1 = 2.",
"announcement": "Compute dp[2, 3] (ba to pac): final characters a and c differ, so add 1 to the left minimum 1 to get 2.",
"state_tables": [
{
"caption": "Edit distance, step 9: full dp table after computing dp[2, 3]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"2, computed",
"1, computed",
"2, computed",
"0, uncomputed initial value"
],
[
"i=3, bag",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-453",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step10.png",
"title": "Compute dp[2, 4] (source prefix ba to target string pack): minimum 3 edits",
"explanation": "At i = 2, j = 4, compute dp[2, 4] for transforming source prefix ba into the full target string pack: the source final character a and target final character k differ, so compare left dp[2, 3] = 2, above dp[1, 4] = 4, and upper-left dp[1, 3] = 3, take the minimum from the left, 2, plus 1, and write dp[2, 4] = 3, completing row 2.",
"key_state": "dp[2, 4] (source prefix ba to target string pack, final characters a and k differ): min(left 2, above 4, upper-left 3) + 1 = 3, completing row 2.",
"announcement": "Compute dp[2, 4] (ba to pack): final characters a and k differ, so add 1 to the left minimum 2 to get 3, completing row 2.",
"state_tables": [
{
"caption": "Edit distance, step 10: full dp table after computing dp[2, 4]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"2, computed",
"1, computed",
"2, computed",
"3, computed"
],
[
"i=3, bag",
"3, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-454",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step11.png",
"title": "Compute dp[3, 1] (source string bag to target prefix p): minimum 3 edits",
"explanation": "Move to row 3 and process i = 3, j = 1 to compute dp[3, 1] for transforming the full source string bag into target prefix p: the source final character g and target final character p differ, so compare left dp[3, 0] = 3, above dp[2, 1] = 2, and upper-left dp[2, 0] = 2, take the minimum 2 plus 1, and write dp[3, 1] = 3.",
"key_state": "dp[3, 1] (source string bag to target prefix p, final characters g and p differ): min(left 3, above 2, upper-left 2) + 1 = 3.",
"announcement": "Move to row 3 and compute dp[3, 1] (bag to p): final characters g and p differ, so take the three-way minimum 2 plus 1 to get 3.",
"state_tables": [
{
"caption": "Edit distance, step 11: full dp table after computing dp[3, 1]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"2, computed",
"1, computed",
"2, computed",
"3, computed"
],
[
"i=3, bag",
"3, valid boundary",
"3, computed",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-455",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step12.png",
"title": "Compute dp[3, 2] (source string bag to target prefix pa): minimum 2 edits",
"explanation": "At i = 3, j = 2, compute dp[3, 2] for transforming the full source string bag into target prefix pa: the source final character g and target final character a differ, so compare left dp[3, 1] = 3, above dp[2, 2] = 1, and upper-left dp[2, 1] = 2, take the minimum from above, 1 (deleting the final g leaves the subproblem of converting ba to pa), plus 1, and write dp[3, 2] = 2.",
"key_state": "dp[3, 2] (source string bag to target prefix pa, final characters g and a differ): min(left 3, above 1, upper-left 2) + 1 = 2.",
"announcement": "Compute dp[3, 2] (bag to pa): final characters g and a differ, so add 1 to the upper minimum 1 to get 2.",
"state_tables": [
{
"caption": "Edit distance, step 12: full dp table after computing dp[3, 2]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"2, computed",
"1, computed",
"2, computed",
"3, computed"
],
[
"i=3, bag",
"3, valid boundary",
"3, computed",
"2, computed",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-456",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step13.png",
"title": "Compute dp[3, 3] (source string bag to target prefix pac): minimum 2 edits",
"explanation": "At i = 3, j = 3, compute dp[3, 3] for transforming the full source string bag into target prefix pac: the source final character g and target final character c differ, so compare left dp[3, 2] = 2, above dp[2, 3] = 2, and upper-left dp[2, 2] = 1, take the upper-left minimum, 1 (once the final g is replaced by c, the remaining subproblem is to convert ba to pa), plus 1, and write dp[3, 3] = 2.",
"key_state": "dp[3, 3] (source string bag to target prefix pac, final characters g and c differ): min(left 2, above 2, upper-left 1) + 1 = 2.",
"announcement": "Compute dp[3, 3] (bag to pac): final characters g and c differ, so add 1 to the upper-left minimum 1 to get 2.",
"state_tables": [
{
"caption": "Edit distance, step 13: full dp table after computing dp[3, 3]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"2, computed",
"1, computed",
"2, computed",
"3, computed"
],
[
"i=3, bag",
"3, valid boundary",
"3, computed",
"2, computed",
"2, computed",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-457",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step14.png",
"title": "Compute dp[3, 4] (source string bag to target string pack): minimum 3 edits",
"explanation": "At the bottom-right cell i = 3, j = 4, compute dp[3, 4] for transforming the full source string bag into the full target string pack: the source final character g and target final character k differ, so compare left dp[3, 3] = 2, above dp[2, 4] = 3, and upper-left dp[2, 3] = 2, take the minimum 2 plus 1, and write dp[3, 4] = 3, completing the entire table.",
"key_state": "dp[3, 4] (source string bag to target string pack, final characters g and k differ): min(left 2, above 3, upper-left 2) + 1 = 3, completing the table.",
"announcement": "Compute bottom-right dp[3, 4] (bag to pack): final characters g and k differ, so take the three-way minimum 2 plus 1 to get 3.",
"state_tables": [
{
"caption": "Edit distance, step 14: full dp table after computing dp[3, 4]",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"2, computed",
"1, computed",
"2, computed",
"3, computed"
],
[
"i=3, bag",
"3, valid boundary",
"3, computed",
"2, computed",
"2, computed",
"3, computed"
]
],
"row_header": 0
}
]
},
{
"id": "source-458",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_dp_step15.png",
"title": "Read bottom-right dp[3, 4] and return the minimum edit count 3",
"explanation": "After all state transitions finish, highlight the bottom-right entry dp[3, 4] = 3 and return it as the minimum number of edits needed to transform the full source string bag into the full target string pack. No other cells are updated in this step; the table gives the minimum edit count without specifying a unique sequence of edits.",
"key_state": "Table complete: bottom-right dp[3, 4] = 3, so transforming bag into pack takes a minimum of 3 edits.",
"announcement": "Table complete; return dp[3, 4] = 3 as the minimum number of edits to transform bag into pack.",
"state_tables": [
{
"caption": "Edit distance, step 15: full dp table returning the final result",
"headers": [
"Source prefix / target prefix",
"j=0, empty string",
"j=1, p",
"j=2, pa",
"j=3, pac",
"j=4, pack"
],
"rows": [
[
"i=0, empty string",
"0, valid boundary",
"1, valid boundary",
"2, valid boundary",
"3, valid boundary",
"4, valid boundary"
],
[
"i=1, b",
"1, valid boundary",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i=2, ba",
"2, valid boundary",
"2, computed",
"1, computed",
"2, computed",
"3, computed"
],
[
"i=3, bag",
"3, valid boundary",
"3, computed",
"2, computed",
"2, computed",
"3, return value"
]
],
"row_header": 0
}
]
}
],
"animations": {
"edit-distance-dp": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-444"
},
{
"id": "step-2",
"frame_id": "source-445"
},
{
"id": "step-3",
"frame_id": "source-446"
},
{
"id": "step-4",
"frame_id": "source-447"
},
{
"id": "step-5",
"frame_id": "source-448"
},
{
"id": "step-6",
"frame_id": "source-449"
},
{
"id": "step-7",
"frame_id": "source-450"
},
{
"id": "step-8",
"frame_id": "source-451"
},
{
"id": "step-9",
"frame_id": "source-452"
},
{
"id": "step-10",
"frame_id": "source-453"
},
{
"id": "step-11",
"frame_id": "source-454"
},
{
"id": "step-12",
"frame_id": "source-455"
},
{
"id": "step-13",
"frame_id": "source-456"
},
{
"id": "step-14",
"frame_id": "source-457"
},
{
"id": "step-15",
"frame_id": "source-458"
}
]
}
}
}

View File

@@ -0,0 +1,50 @@
{
"schema_version": 2,
"title": "Edit distance: two three-step transformation examples",
"summary": "The alignments show how kitten becomes sitting and how hello becomes algo. Each transformation takes at least 3 edits, and the examples achieve that minimum.",
"context": [
"Each edit may insert, delete, or replace one character."
],
"description": [
"The figure places two character-by-character alignment diagrams side by side; from top to bottom, each shows the source string row, an intermediate edited row, and the target string row. In both diagrams, arrows indicate the edit type and positional correspondence at each character without prescribing a unique order for the three edits.",
"On the left, source string s = kitten is transformed into target string t = sitting: the first letter k is replaced with s (blue), the 5th letter e is replaced with i (blue), and the letter g is inserted at the end (purple); the other 4 unchanged letters i, t, t, and n remain as they are, with vertical dashed lines aligning the intermediate row to the target row. The intermediate row reads s, i, t, t, i, n, g, with the replacements s and i in blue and the inserted g in purple, already matching the target string. Counting characters, the length changes from 6 to 7.",
"On the right, source string s = hello is transformed into target string t = algo: the first letter h is deleted (shown faded in light orange in the intermediate row and not carried down into the target string), the 2nd letter e is replaced with a (blue), and the second of the two consecutive l letters is replaced with g (blue), while the first l and the final o remain unchanged, with vertical dashed lines aligning the intermediate row to the target row. The intermediate row keeps the faded h followed by a, l, g, o, whereas the target row keeps only a, l, g, o. Counting characters, the length changes from 5 to 4."
],
"frames": [
{
"id": "source-441",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_example.png",
"title": "Character-by-character alignment for two three-step edit examples",
"explanation": "The drawing does not label the total edit count directly; the count of 3 in the table comes from adding two replacements and one insertion or deletion in each example, matching the minimum number of edits stated in the text."
}
],
"tables": [
{
"caption": "Edits in the two examples",
"headers": [
"Source",
"Target",
"Replacements",
"Insertion or deletion",
"Edits"
],
"rows": [
[
"kitten",
"sitting",
"k → s; e → i",
"Insert g at end",
"3"
],
[
"hello",
"algo",
"e → a; second l → g",
"Delete leading h",
"3"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,57 @@
{
"schema_version": 2,
"title": "State transitions for edit distance",
"summary": "When transforming book into code, the last characters k and e differ. Insertion, deletion, and replacement each leave a different pair of prefixes to transform.",
"context": [
"Let state dp[i, j] be the minimum number of edits needed to transform the first i characters of source string s into the first j characters of target string t, where each insertion, deletion, or replacement costs 1. Using s = book and t = code (current prefix lengths i = 4 and j = 4), this figure examines where the state transitions come from when the current final characters s[i-1] = k and t[j-1] = e differ."
],
"description": [
"On the left is the current state dp[i, j], and on the right from top to bottom are the three branches for insertion (appending), deletion, and replacement. Grayed-out final characters indicate characters already matched or deleted and no longer part of the remaining prefixes to be solved.",
"After insertion, the newly appended final character matches and cancels the target's final character without consuming any character of the original source string, so only j decreases by 1. Deletion removes only the source's final character, so only i decreases by 1. After replacement, the two final characters match and cancel each other, so both i and j decrease by 1.",
"Following the three branches in order, the table below distinguishes \"Source after edit\" from \"Remaining source prefix\" and lists the corresponding subproblem state; the figure does not compute the final edit distance from book to code."
],
"frames": [
{
"id": "source-443",
"book_path": "chapter_dynamic_programming/edit_distance_problem.assets/edit_distance_state_transfer.png",
"title": "Three edit operations reduce the problem to different remaining prefixes",
"explanation": "Each of the three operations costs 1 edit, and we choose whichever leaves the fewest edits in its remaining subproblem; therefore, when the final characters differ, dp[i,j] = min(dp[i,j-1], dp[i-1,j], dp[i-1,j-1]) + 1."
}
],
"tables": [
{
"caption": "Three operations and remaining prefixes when the final characters differ",
"headers": [
"Operation",
"Source after edit",
"Remaining source prefix",
"Remaining target prefix",
"Subproblem state"
],
"rows": [
[
"Insert e",
"booke",
"book",
"cod",
"dp[i,j-1]"
],
[
"Delete k",
"boo",
"boo",
"code",
"dp[i-1,j]"
],
[
"Replace k with e",
"booe",
"boo",
"cod",
"dp[i-1,j-1]"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,71 @@
{
"schema_version": 2,
"title": "Memoized search reuses previously computed states",
"summary": "On the first visit, memoized search computes and caches each non-base state along the left branch. When a right branch reaches the same state, its cached value still contributes to the parent’s sum.",
"context": [
"Again counting ways to climb stairs by taking 1 or 2 steps at a time, with base cases dp[1] = 1 and dp[2] = 2, memoized search introduces an array mem to record computed non-base state values: base cases return immediately, while non-base states check mem first and expand further only if not yet recorded."
],
"description": [
"In the figure, the main first-time computation chain runs dp[9] → dp[8] → dp[7] → ... → dp[3], with dp[6] through dp[4] condensed as ellipses; dp[3] then splits into the base cases dp[2] and dp[1]. On the right, scissors icons explicitly mark cached reuse at dp[7], dp[6], and dp[5], while remaining reuse points are summarized by ellipses. Filling in the omitted segment from the code also reuses dp[4] inside dp[6] and dp[3] inside dp[5]; the right subproblem dp[2] of dp[4] returns directly as a base case rather than a cache hit.",
"For example, computing dp[9] first completes its left subproblem dp[8], during which dp[7] is already computed and stored; when evaluating the right subproblem (dp[7] marked with scissors), the search reads the cached value directly without expanding it again, and that value still contributes to the sum for dp[9].",
"The two tables below list the three reuse relationships explicitly shown in the figure and how the code handles base cases, first-time computations, and cache hits."
],
"frames": [
{
"id": "source-370",
"book_path": "chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_memo_tree.png",
"title": "Memoized search reuses previously computed states",
"explanation": "Each non-base state is expanded and computed only once, and repeated lookups return the cached value directly, reducing the time complexity to O(n)."
}
],
"tables": [
{
"caption": "Cached state reuses explicitly shown in the figure",
"headers": [
"Parent state",
"Left subproblem completed first",
"Right subproblem read from cache"
],
"rows": [
[
"dp[9]",
"dp[8]",
"dp[7]"
],
[
"dp[8]",
"dp[7]",
"dp[6]"
],
[
"dp[7]",
"dp[6] (shown as an ellipsis in the figure)",
"dp[5]"
]
],
"row_header": 0
},
{
"caption": "Handling of the three kinds of states",
"headers": [
"Encountered state",
"Action"
],
"rows": [
[
"dp[1], dp[2]",
"Return 1 or 2 directly"
],
[
"Non-base state, not yet recorded",
"Compute recursively, sum, store in mem, and return"
],
[
"Non-base state, already recorded",
"Return the value from mem directly; still added into parent sum"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,103 @@
{
"schema_version": 2,
"title": "Overlapping subproblems in brute-force climbing stairs search",
"summary": "When brute-force recursion splits top-down from dp[9], identical subproblems do not share results and are repeatedly expanded across different branches.",
"context": [
"In the climbing stairs problem, each move climbs 1 or 2 steps, and dp[i] denotes the number of ways to reach step i. Brute-force search recursively decomposes each state using dp[i] = dp[i - 1] + dp[i - 2] until reaching the base cases dp[1] = 1 or dp[2] = 2."
],
"description": [
"Computing dp[9] requires dp[8] and dp[7], and computing dp[8] again requires dp[7] and dp[6]. The two occurrences of dp[7] in the brute-force tree do not share a single computation; each occurrence is expanded and solved all over again.",
"The figure draws only the first four levels, with 15 state nodes in total, and 16 ellipses along the bottom indicating continued recursion down to the base cases dp[1] or dp[2]. Counts in the table (such as dp[5] appearing 4 times) cover only the four drawn levels, not the full recursion.",
"The tables below first list the four drawn levels and then summarize by state. Left and right subproblems in the decomposition table follow the recurrence; the children of every level-4 node are shown only as ellipses in the figure rather than drawn individually. In particular, dp[4] and dp[3] appear only on level 4, so their subproblems in those two rows come from the recurrence and are not drawn in the figure."
],
"frames": [
{
"id": "source-369",
"book_path": "chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_tree.png",
"title": "Overlapping subproblems in brute-force climbing stairs search",
"explanation": "The caption at the bottom of the figure connects overlapping subproblems to exponential runtime: brute-force recursion repeatedly solves the same states, resulting in an O(2ⁿ) time bound, where 2ⁿ means 2 to the power n."
}
],
"tables": [
{
"caption": "Recursive states across the four levels shown",
"headers": [
"Level (root is level 1)",
"States (left to right)"
],
"rows": [
[
"1",
"dp[9]"
],
[
"2",
"dp[8], dp[7]"
],
[
"3",
"dp[7], dp[6], dp[6], dp[5]"
],
[
"4",
"dp[6], dp[5], dp[5], dp[4], dp[5], dp[4], dp[4], dp[3]"
]
],
"row_header": 0
},
{
"caption": "Decomposition and occurrence counts in the first four levels",
"headers": [
"State",
"Left subproblem",
"Right subproblem",
"Count in first four levels"
],
"rows": [
[
"dp[9]",
"dp[8]",
"dp[7]",
"1"
],
[
"dp[8]",
"dp[7]",
"dp[6]",
"1"
],
[
"dp[7]",
"dp[6]",
"dp[5]",
"2"
],
[
"dp[6]",
"dp[5]",
"dp[4]",
"3"
],
[
"dp[5]",
"dp[4]",
"dp[3]",
"4"
],
[
"dp[4]",
"dp[3]",
"dp[2]",
"3"
],
[
"dp[3]",
"dp[2]",
"dp[1]",
"1"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,78 @@
{
"schema_version": 2,
"title": "Iteratively computing ways to climb stairs from initial states",
"summary": "Starting from the initial states dp[1] = 1 and dp[2] = 2, repeatedly sum the two preceding entries from left to right up to dp[9].",
"context": [
"Each move climbs 1 or 2 steps, and dp[i] denotes the number of ways to reach step i. This figure shows bottom-up dynamic programming filling the table iteratively without a recursion call stack."
],
"description": [
"First set dp[1] = 1 and dp[2] = 2, then compute dp[i] = dp[i - 1] + dp[i - 2] in order from dp[3] through dp[9]: each entry depends only on the preceding two entries, both of which have already been computed when needed.",
"Nine cells are arranged horizontally in the figure, labeled only with the state names dp[1] through dp[9], while the initial values dp[1] = 1, dp[2] = 2 and the state transition equation are written below. The values 3, 5, 8, 13, 21, 34, and finally 55 at dp[9] are derived from those initial values and the equation rather than printed inside the cells. The table below lists each state's initial value or dependency together with its derived value."
],
"frames": [
{
"id": "source-371",
"book_path": "chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dp.png",
"title": "Iteratively computing ways to climb stairs from initial states",
"explanation": "Bottom-up iteration computes each state only once and stops upon reaching the target state; from the initial values and transition equation in the figure, the target state dp[9] evaluates to 55 ways."
}
],
"tables": [
{
"caption": "Dependencies and values derived from the recurrence",
"headers": [
"State",
"Source",
"Value and basis"
],
"rows": [
[
"dp[1]",
"Initial state",
"1 (initial value given in figure)"
],
[
"dp[2]",
"Initial state",
"2 (initial value given in figure)"
],
[
"dp[3]",
"dp[2] + dp[1]",
"3 (derived from equation)"
],
[
"dp[4]",
"dp[3] + dp[2]",
"5 (derived from equation)"
],
[
"dp[5]",
"dp[4] + dp[3]",
"8 (derived from equation)"
],
[
"dp[6]",
"dp[5] + dp[4]",
"13 (derived from equation)"
],
[
"dp[7]",
"dp[6] + dp[5]",
"21 (derived from equation)"
],
[
"dp[8]",
"dp[7] + dp[6]",
"34 (derived from equation)"
],
[
"dp[9]",
"dp[8] + dp[7]",
"55 (derived from equation)"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,19 @@
{
"schema_version": 2,
"title": "Three ways to climb to the third step",
"summary": "Three step-by-step paths show the distinct ways to reach step 3.",
"context": [
"Numbering the ground level as 0, each move climbs 1 or 2 steps, with the goal of landing on step 3."
],
"description": [
"From left to right, the stairs are numbered 0 through 6, with the tread of target step 3 highlighted in green. Three sets of jump arcs are drawn above the same staircase, matching the step sequences listed below; a caption beneath the staircase notes, \"There are 3 ways to reach step 3.\""
],
"frames": [
{
"id": "source-367",
"book_path": "chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_example.png",
"title": "Three ways to climb to the third step",
"explanation": "The solid cyan path advances along steps 0 → 1 → 2 → 3, climbing 1 step three times in a row; the dotted blue path follows 0 → 2 → 3, climbing 2 steps to step 2 and then 1 step to step 3; the dashed orange path follows 0 → 1 → 3, climbing 1 step to step 1 and then 2 steps to step 3. Climbing 2 steps then 1 step visits a different intermediate step from climbing 1 step then 2 steps, so the two count as distinct ways."
}
]
}

View File

@@ -0,0 +1,55 @@
{
"schema_version": 2,
"title": "Counting ways to reach step 5 from the counts for steps 3 and 4",
"summary": "The final move onto step 5 must come from either step 3 or step 4, giving 3 + 5 = 8 ways.",
"context": [
"Because each move climbs only 1 or 2 steps, let dp[n] be the number of ways to reach step n, with initial states dp[1] = 1 and dp[2] = 2."
],
"description": [
"Steps 3, 4, and 5 on the staircase are highlighted in green, cyan, and blue, respectively. First, 3 dashed green arcs converge on step 3 (labeled dp[3] = 3) and 5 solid cyan arcs converge on step 4 (labeled dp[4] = 5); from there, a single dashed green arc spanning 2 steps and a single solid cyan arc spanning 1 step converge on step 5. The equation dp[5] = dp[3] + dp[4] = 8 appears at the top, and a row at the bottom pairs steps 1 through 6 with their numbers of ways."
],
"frames": [
{
"id": "source-368",
"book_path": "chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_state_transfer.png",
"title": "Counting ways to reach step 5 from the counts for steps 3 and 4",
"explanation": "To reach step 5, the final move either jumps 2 steps up from step 3 or jumps 1 step up from step 4. Extending each of the 3 ways to reach step 3 with a 2-step jump produces 3 ways to reach step 5; extending each of the 5 ways to reach step 4 with a 1-step jump produces another 5 ways. Because these two groups differ in the step preceding the final move, they are mutually exclusive and collectively exhaustive, so dp[5] = dp[3] + dp[4] = 3 + 5 = 8. More generally, for any step i (i ≥ 3), dp[i] = dp[i-1] + dp[i-2]."
}
],
"tables": [
{
"caption": "Steps and numbers of ways shown in the figure",
"headers": [
"Number of steps n",
"Number of ways dp[n]"
],
"rows": [
[
"1",
"1"
],
[
"2",
"2"
],
[
"3",
"3"
],
[
"4",
"5"
],
[
"5",
"8"
],
[
"6",
"13"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,145 @@
{
"schema_version": 2,
"title": "Repeated recursion in 0-1 knapsack",
"summary": "In a dedicated three-item example with capacity 30, two different decision paths reach dp[1, 10]. Each expands its subtree once, so it is expanded twice in total.",
"context": [
"In 0-1 knapsack, each item may be chosen at most once. Note that this figure uses a separate 3-item example distinct from the earlier figure and the main driver code: knapsack capacity cap = 30, and the 3 items have weights 10, 20, 20 and values 60, 110, 120 (see the table). State dp[i, c] denotes the maximum value obtainable from the first i items with remaining capacity c; the table header in the drawing writes wgt[i] and val[i] (with item IDs i starting at 1), whereas the code in the text indexes the arrays at i - 1.",
"When the current item fits, compare dp[i-1, c] (excluding it) with dp[i-1, c-wgt[i-1]] + val[i-1] (including it) and take the larger value; when it does not fit, take only the exclude branch. With no items left (i = 0) or remaining capacity 0 (c = 0), return 0."
],
"description": [
"Recursion starts at the root dp[3, 30] and makes decisions in order for item 3 (pineapple, weight 20, value 120), item 2 (watermelon, weight 20, value 110), and item 1 (apple, weight 10, value 60). Because item 2 and item 3 both have weight 20, taking either \"exclude item 3, then include item 2\" (dp[3, 30] → dp[2, 30] → dp[1, 10]) or \"include item 3, then exclude item 2\" (dp[3, 30] → dp[2, 10] → dp[1, 10]) subtracts weight 20, leaves capacity 10, and leaves only item 1 to consider, so the two distinct paths converge on the same subproblem dp[1, 10].",
"Brute-force search does not record previously solved subproblems, so upon encountering the two occurrences of dp[1, 10], it expands each one downward separately, comparing dp[0, 10] (excluding item 1) with dp[0, 0] + 60 (including item 1) both times; thus the same subproblem dp[1, 10] is expanded twice in full, making the second expansion redundant.",
"At the right child dp[2, 10], the remaining capacity is 10 while item 2 has weight 20, exceeding the remaining capacity. The node dp[1, -10] drawn in the figure is labeled \"Prune: item weight > knapsack capacity\" solely to illustrate the excluded overweight branch; the code in the text checks whether the item weight exceeds the remaining capacity before recursing, calling only the exclude branch dp[1, 10] when overweight rather than making a call with negative capacity.",
"The two tables below list the dedicated input items and the complete recursion tree shown in the figure; using the decision path from the root as the row header distinguishes multiple occurrences of the same state."
],
"frames": [
{
"id": "source-395",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dfs.png",
"title": "Two decision paths repeatedly expand subproblem dp[1, 10]",
"explanation": "The figure contains 13 nodes in total, including 6 base-case leaf nodes that return 0 and 1 illustrative overweight node. From the input data, choosing item 1 and item 3 gives total weight 10 + 20 = 30 and maximum value 60 + 120 = 180; the value 180 is not written directly on the tree nodes."
}
],
"tables": [
{
"caption": "Three items used in the recursion tree; capacity 30",
"headers": [
"Item ID",
"Illustrated item",
"Weight",
"Value"
],
"rows": [
[
"1",
"Apple",
"10",
"60"
],
[
"2",
"Watermelon",
"20",
"110"
],
[
"3",
"Pineapple",
"20",
"120"
]
],
"row_header": 0
},
{
"caption": "Complete recursion tree; paths start at the root and include the excluded negative-capacity node",
"headers": [
"Decision path",
"State",
"Action or return",
"Child states and value gain"
],
"rows": [
[
"Root",
"dp[3,30]",
"Compare total values of excluding and including",
"Exclude: dp[2,30]; Include: dp[2,10]+120"
],
[
"Exclude 3",
"dp[2,30]",
"Compare total values of excluding and including",
"Exclude: dp[1,30]; Include: dp[1,10]+110"
],
[
"Exclude 3 → Exclude 2",
"dp[1,30]",
"Compare total values of excluding and including",
"Exclude: dp[0,30]; Include: dp[0,20]+60"
],
[
"Exclude 3 → Exclude 2 → Exclude 1",
"dp[0,30]",
"Base case, return 0",
"Not expanded"
],
[
"Exclude 3 → Exclude 2 → Include 1",
"dp[0,20]",
"Base case, return 0",
"Not expanded"
],
[
"Exclude 3 → Include 2",
"dp[1,10]",
"Compare total values of excluding and including",
"Exclude: dp[0,10]; Include: dp[0,0]+60"
],
[
"Exclude 3 → Include 2 → Exclude 1",
"dp[0,10]",
"Base case, return 0",
"Not expanded"
],
[
"Exclude 3 → Include 2 → Include 1",
"dp[0,0]",
"Base case, return 0",
"Not expanded"
],
[
"Include 3",
"dp[2,10]",
"Overweight, take only the exclude branch",
"Exclude: dp[1,10]; Include: dp[1,-10] (excluded)"
],
[
"Include 3 → Exclude 2",
"dp[1,10]",
"Compare total values of excluding and including",
"Exclude: dp[0,10]; Include: dp[0,0]+60"
],
[
"Include 3 → Exclude 2 → Exclude 1",
"dp[0,10]",
"Base case, return 0",
"Not expanded"
],
[
"Include 3 → Exclude 2 → Include 1",
"dp[0,0]",
"Base case, return 0",
"Not expanded"
],
[
"Include 3 → Include 2",
"dp[1,-10]",
"Illustrative overweight branch; not actually called",
"Not expanded"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,133 @@
{
"schema_version": 2,
"title": "Memoized search for 0-1 knapsack",
"summary": "When reaching dp[1, 10] again along the path that includes item 3, the search returns the cached result directly and skips the duplicate subtree; this differs in meaning from overweight pruning.",
"context": [
"In 0-1 knapsack, each item may be chosen at most once. This figure uses the same dedicated 3-item example with capacity cap = 30 as the preceding figure: weights 10, 20, 20 and values 60, 110, 120 (see the table). State dp[i, c] denotes the maximum value obtainable from the first i items with available capacity c; the table header in the drawing writes wgt[i] and val[i] (with i from 1 to 3), whereas the code in the text indexes the arrays at i - 1.",
"When the current item fits, compare dp[i-1, c] (excluding it) with dp[i-1, c-wgt[i-1]] + val[i-1] (including it) and take the larger value; when it does not fit, take only the exclude branch. With no items left (i = 0) or remaining capacity 0 (c = 0), return 0."
],
"description": [
"Decisions proceed from the root dp[3, 30] for items 3, 2, and 1 in turn. Because item 2 (watermelon) and item 3 (pineapple) both weigh 20, either \"exclude item 3, then include item 2\" or \"include item 3, then exclude item 2\" leaves capacity 10 with only item 1 (apple, weight 10, value 60) remaining, so both paths converge on the same state dp[1, 10].",
"When the left subtree first visits dp[1, 10] (path \"Exclude 3 → Include 2\"), it expands to compare dp[0, 10] with dp[0, 0] + 60 and stores the result in the cache; when the right subtree under dp[2, 10] chooses to exclude item 2 and encounters dp[1, 10] again (path \"Include 3 → Exclude 2\"), it triggers \"Prune: cached result found\" and returns the cached value directly without expanding the two leaf nodes again. From item 1's weight 10 and value 60, that cached return value is 60—derived from the input table rather than written on the node.",
"Under the right child dp[2, 10], both branches carry scissors icons, yet they stop for completely different reasons: the left branch dp[1, 10] is a cache hit that directly returns the valid subproblem solution 60, whereas the right branch dp[1, -10] (\"Prune: item weight > knapsack capacity\") is an invalid illustrative node excluded because item 2's weight 20 exceeds the remaining capacity 10; the code checks for overweight before recursing and calls only the exclude branch dp[1, 10], never actually calling dp[1, -10].",
"The two tables below list the dedicated input items and the complete recursion tree shown in the figure; using the decision path from the root as the row header distinguishes multiple occurrences of the same state."
],
"frames": [
{
"id": "source-396",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dfs_mem.png",
"title": "Cache hit reuses dp[1, 10], distinct from overweight pruning",
"explanation": "The figure contains 11 nodes in total, reducing the base-case leaf nodes from 6 in the brute-force tree to 4; the global maximum value remains 180 from choosing item 1 and item 3. Both the cached value 60 and the maximum value 180 are derived from the input data rather than printed on the tree nodes."
}
],
"tables": [
{
"caption": "Three items used in the recursion tree; capacity 30",
"headers": [
"Item ID",
"Illustrated item",
"Weight",
"Value"
],
"rows": [
[
"1",
"Apple",
"10",
"60"
],
[
"2",
"Watermelon",
"20",
"110"
],
[
"3",
"Pineapple",
"20",
"120"
]
],
"row_header": 0
},
{
"caption": "Complete recursion tree; paths start at the root and include the excluded negative-capacity node",
"headers": [
"Decision path",
"State",
"Action or return",
"Child states and value gain"
],
"rows": [
[
"Root",
"dp[3,30]",
"Compare total values of excluding and including",
"Exclude: dp[2,30]; Include: dp[2,10]+120"
],
[
"Exclude 3",
"dp[2,30]",
"Compare total values of excluding and including",
"Exclude: dp[1,30]; Include: dp[1,10]+110"
],
[
"Exclude 3 → Exclude 2",
"dp[1,30]",
"Compare total values of excluding and including",
"Exclude: dp[0,30]; Include: dp[0,20]+60"
],
[
"Exclude 3 → Exclude 2 → Exclude 1",
"dp[0,30]",
"Base case, return 0",
"Not expanded"
],
[
"Exclude 3 → Exclude 2 → Include 1",
"dp[0,20]",
"Base case, return 0",
"Not expanded"
],
[
"Exclude 3 → Include 2",
"dp[1,10]",
"Compare total values of excluding and including",
"Exclude: dp[0,10]; Include: dp[0,0]+60"
],
[
"Exclude 3 → Include 2 → Exclude 1",
"dp[0,10]",
"Base case, return 0",
"Not expanded"
],
[
"Exclude 3 → Include 2 → Include 1",
"dp[0,0]",
"Base case, return 0",
"Not expanded"
],
[
"Include 3",
"dp[2,10]",
"Overweight, take only the exclude branch",
"Exclude: dp[1,10]; Include: dp[1,-10] (excluded)"
],
[
"Include 3 → Exclude 2",
"dp[1,10]",
"Cache hit, return 60 (derived from input)",
"Not expanded"
],
[
"Include 3 → Include 2",
"dp[1,-10]",
"Illustrative overweight branch; not actually called",
"Not expanded"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,271 @@
{
"schema_version": 2,
"title": "Dynamic programming for 0-1 knapsack",
"summary": "With three items that may each be chosen at most once, this example steps cell by cell through the 0-1 knapsack recurrence and finds a maximum total value of 20 at capacity 4.",
"context": [
"There are 3 candidate items (n = 3), whose IDs, names, weights, and values are given in the input table. With knapsack capacity cap = 4, the goal is to maximize total value without exceeding capacity; the knapsack need not be filled completely.",
"State dp[i, c] denotes the maximum value obtainable from the first i items with total weight at most capacity c. Row index i runs from 0 to 3 and column index c runs from 0 to 4, forming a 4-row by 5-column state table; item IDs i start at 1 and correspond to array weight wgt[i-1] and value val[i-1]."
],
"description": [
"Step 1 initializes the table; steps 2 to 5, 6 to 9, and 10 to 13 compute rows 1, 2, and 3 across capacities c = 1 to 4; step 14 returns the answer. Each non-boundary cell is computed once and never modified afterward. Cells in the final table include the step number at which they are first computed: before that step, a cell holds the uncomputed initial value 0; from that step onward, it holds the final value shown in the table.",
"For item i, write w for its weight and v for its value. If w > c, the item does not fit and must be excluded, inheriting dp[i-1, c] directly above; otherwise compare dp[i-1, c] (excluding it) with dp[i-1, c-w] + v (including it), found in the previous row shifted w columns to the left. Both sources come from the previous row, which has not yet included item i, ensuring each item is chosen at most once."
],
"frames": [
{
"id": "source-397",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step1.png",
"title": "Initialize the 4×5 state matrix",
"explanation": "Create a 4-row by 5-column dp table filled initially with 0. Row 0 (no items) and column 0 (zero capacity) hold settled boundary values of 0, shown in dark text in the figure; the remaining 12 cells hold uncomputed initial values of 0, shown in faint text, and must not be read as computed optimal values.",
"key_state": "Initialize the 4×5 dp table to all 0: the first row and first column are valid boundaries of 0, while the other 12 cells hold uncomputed initial values of 0.",
"announcement": "Initialize the 4×5 dp matrix and set the no-item first row and zero-capacity first column boundaries to 0."
},
{
"id": "source-398",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step2.png",
"title": "Compute dp[1, 1], getting 5",
"explanation": "Consider only the first item at capacity 1, where the current item is the apple (weight 1, value 5). Excluding it gives dp[0, 1] = 0 from the previous row; including it leaves capacity 1 - 1 = 0, looks up dp[0, 0] = 0 in the previous row (the first 0 items), and adds value 5 to get 5. Take the larger value 5 and write it to dp[1, 1]. Before this cell lie only the initialized boundary cells, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "Only the first item (apple), capacity 1: include the apple, setting dp[1, 1] to 5; later non-boundary cells still hold uncomputed initial values of 0.",
"announcement": "Compute dp[1, 1] (the first item only, capacity 1): including the apple beats excluding it, so write maximum value 5."
},
{
"id": "source-399",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step3.png",
"title": "Compute dp[1, 2], getting 5",
"explanation": "Consider only the first item at capacity 2, where the current item is the apple (weight 1, value 5). Excluding it gives dp[0, 2] = 0 from the previous row; including it leaves capacity 2 - 1 = 1, looks up dp[0, 1] = 0 in the previous row (the first 0 items), and adds value 5 to get 5. Take the larger value 5 and write it to dp[1, 2]. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "Only the first item (apple), capacity 2: the apple may be chosen only once, so dp[1, 2] is 5; later non-boundary cells still hold uncomputed initial values of 0.",
"announcement": "Compute dp[1, 2] (the first item only, capacity 2): the apple may be chosen at most once, so write maximum value 5."
},
{
"id": "source-400",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step4.png",
"title": "Compute dp[1, 3], getting 5",
"explanation": "Consider only the first item at capacity 3, where the current item is the apple (weight 1, value 5). Excluding it gives dp[0, 3] = 0 from the previous row; including it leaves capacity 3 - 1 = 2, looks up dp[0, 2] = 0 in the previous row (the first 0 items), and adds value 5 to get 5. Take the larger value 5 and write it to dp[1, 3]. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "Only the first item (apple), capacity 3: dp[1, 3] is computed as 5; later non-boundary cells still hold uncomputed initial values of 0.",
"announcement": "Compute dp[1, 3] (the first item only, capacity 3): include one apple and write maximum value 5."
},
{
"id": "source-401",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step5.png",
"title": "Compute dp[1, 4], getting 5",
"explanation": "Consider only the first item at capacity 4, where the current item is the apple (weight 1, value 5). Excluding it gives dp[0, 4] = 0 from the previous row; including it leaves capacity 4 - 1 = 3, looks up dp[0, 3] = 0 in the previous row (the first 0 items), and adds value 5 to get 5. Take the larger value 5 and write it to dp[1, 4]. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "Only the first item (apple), capacity 4: dp[1, 4] is computed as 5, completing row 1; cells in rows 2 and 3 with capacity greater than 0 still hold uncomputed initial values of 0.",
"announcement": "Compute dp[1, 4] (the first item only, capacity 4): write maximum value 5, completing row 1."
},
{
"id": "source-402",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step6.png",
"title": "Compute dp[2, 1], getting 5",
"explanation": "Consider the first 2 items at capacity 1, where the current item is the pineapple (weight 2, value 11). Since weight 2 exceeds capacity 1, it does not fit and must be excluded; inherit dp[1, 1] = 5 from the previous row and write dp[2, 1] = 5. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "First 2 items (through pineapple), capacity 1: the weight-2 pineapple does not fit, so dp[2, 1] is 5; later non-boundary cells still hold uncomputed initial values of 0.",
"announcement": "Compute dp[2, 1] (first 2 items, capacity 1): the pineapple does not fit, so inherit value 5 from the previous row."
},
{
"id": "source-403",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step7.png",
"title": "Compute dp[2, 2], getting 11",
"explanation": "Consider the first 2 items at capacity 2, where the current item is the pineapple (weight 2, value 11). Excluding it gives dp[1, 2] = 5 from the previous row; including it leaves capacity 2 - 2 = 0, looks up dp[1, 0] = 0 in the previous row (the first item only), and adds value 11 to get 11. Take the larger value 11 and write it to dp[2, 2]. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "First 2 items (through pineapple), capacity 2: include the pineapple, setting dp[2, 2] to 11; later non-boundary cells still hold uncomputed initial values of 0.",
"announcement": "Compute dp[2, 2] (first 2 items, capacity 2): including the pineapple (11) beats excluding it (5), so write maximum value 11."
},
{
"id": "source-404",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step8.png",
"title": "Compute dp[2, 3], getting 16",
"explanation": "Consider the first 2 items at capacity 3, where the current item is the pineapple (weight 2, value 11). Excluding it gives dp[1, 3] = 5 from the previous row; including it leaves capacity 3 - 2 = 1, looks up dp[1, 1] = 5 in the previous row (the first item only), and adds value 11 to get 16. Take the larger value 16 and write it to dp[2, 3]. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "First 2 items, capacity 3: including the pineapple gives 16, beating 5 when excluded, so dp[2, 3] = 16. Later non-boundary cells still hold uncomputed initial values of 0.",
"announcement": "Compute dp[2, 3]: including the pineapple gives 16, beating 5 when excluded, so write 16."
},
{
"id": "source-405",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step9.png",
"title": "Compute dp[2, 4], getting 16",
"explanation": "Consider the first 2 items at capacity 4, where the current item is the pineapple (weight 2, value 11). Excluding it gives dp[1, 4] = 5 from the previous row; including it leaves capacity 4 - 2 = 2, looks up dp[1, 2] = 5 in the previous row (the first item only), and adds value 11 to get 16. Take the larger value 16 and write it to dp[2, 4]. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "First 2 items, capacity 4: including the pineapple gives 16, beating 5 when excluded, so dp[2, 4] = 16. Later non-boundary cells still hold uncomputed initial values of 0.",
"announcement": "Compute dp[2, 4]: including the pineapple gives 16, beating 5 when excluded, so write 16."
},
{
"id": "source-406",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step10.png",
"title": "Compute dp[3, 1], getting 5",
"explanation": "Consider the first 3 items at capacity 1, where the current item is the watermelon (weight 3, value 15). Since weight 3 exceeds capacity 1, it does not fit and must be excluded; inherit dp[2, 1] = 5 from the previous row and write dp[3, 1] = 5. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "First 3 items (through watermelon), capacity 1: the weight-3 watermelon does not fit, so dp[3, 1] is 5; later non-boundary cells still hold uncomputed initial values of 0.",
"announcement": "Compute dp[3, 1] (first 3 items, capacity 1): the watermelon does not fit, so inherit value 5 from the previous row."
},
{
"id": "source-407",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step11.png",
"title": "Compute dp[3, 2], getting 11",
"explanation": "Consider the first 3 items at capacity 2, where the current item is the watermelon (weight 3, value 15). Since weight 3 exceeds capacity 2, it does not fit and must be excluded; inherit dp[2, 2] = 11 from the previous row and write dp[3, 2] = 11. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "First 3 items (through watermelon), capacity 2: the weight-3 watermelon still does not fit, so dp[3, 2] is 11; later non-boundary cells still hold uncomputed initial values of 0.",
"announcement": "Compute dp[3, 2] (first 3 items, capacity 2): the watermelon still does not fit, so inherit value 11 from the previous row."
},
{
"id": "source-408",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step12.png",
"title": "Compute dp[3, 3], getting 16",
"explanation": "Consider the first 3 items at capacity 3, where the current item is the watermelon (weight 3, value 15). Excluding it gives dp[2, 3] = 16 from the previous row; including it leaves capacity 3 - 3 = 0, looks up dp[2, 0] = 0 in the previous row (the first 2 items), and adds value 15 to get 15. Take the larger value 16 and write it to dp[3, 3]. Earlier cells are already computed, and later non-boundary cells still hold uncomputed initial values of 0.",
"key_state": "First 3 items (through watermelon), capacity 3: excluding the watermelon (16) beats taking the watermelon alone (15), setting dp[3, 3] to 16; only dp[3, 4] remains at its uncomputed initial value 0.",
"announcement": "Compute dp[3, 3] (first 3 items, capacity 3): 16 from excluding the watermelon beats 15 from taking the watermelon alone, so write maximum value 16."
},
{
"id": "source-409",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step13.png",
"title": "Compute dp[3, 4], getting 20",
"explanation": "Consider the first 3 items at capacity 4, where the current item is the watermelon (weight 3, value 15). Excluding it gives dp[2, 4] = 16 from the previous row; including it leaves capacity 4 - 3 = 1, looks up dp[2, 1] = 5 in the previous row (the first 2 items), and adds value 15 to get 20. Take the larger value 20 and write it to dp[3, 4]. All 12 non-boundary cells have now been computed.",
"key_state": "First 3 items, capacity 4: including the watermelon gives 20, beating 16 when excluded, so dp[3, 4] = 20. All non-boundary cells are now computed.",
"announcement": "Compute dp[3, 4]: including the watermelon gives 20, beating 16 when excluded, so write 20."
},
{
"id": "source-410",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_step14.png",
"title": "Return maximum value 20 for capacity 4",
"explanation": "Read bottom-right dp[3, 4] = 20, choosing the apple and the watermelon: total weight 1 + 3 = 4, total value 5 + 15 = 20. The final frame's note \"Return the maximum achievable knapsack value after considering all items: 20\" means the optimal subset chosen from all three candidate items; packing all three would weigh 6, exceeding capacity 4.",
"key_state": "Table complete; return bottom-right dp[3, 4] = 20 (choosing the apple and the watermelon).",
"announcement": "All states computed; return the maximum value at capacity 4, dp[3, 4] = 20."
}
],
"tables": [
{
"caption": "Item input data for this figure",
"headers": [
"Item ID i",
"Item",
"Weight wgt[i - 1]",
"Value val[i - 1]"
],
"rows": [
[
"1",
"Apple",
"1",
"5"
],
[
"2",
"Pineapple",
"2",
"11"
],
[
"3",
"Watermelon",
"3",
"15"
]
],
"row_header": 0
},
{
"caption": "Completed dp maximum values and first-computed steps",
"headers": [
"Available items (first i)",
"Capacity c=0",
"Capacity c=1",
"Capacity c=2",
"Capacity c=3",
"Capacity c=4"
],
"rows": [
[
"No items (i=0)",
"0 (valid boundary)",
"0 (valid boundary)",
"0 (valid boundary)",
"0 (valid boundary)",
"0 (valid boundary)"
],
[
"Apple (i=1)",
"0 (valid boundary)",
"5 (step 2)",
"5 (step 3)",
"5 (step 4)",
"5 (step 5)"
],
[
"Apple, pineapple (i=2)",
"0 (valid boundary)",
"5 (step 6)",
"11 (step 7)",
"16 (step 8)",
"16 (step 9)"
],
[
"Apple, pineapple, watermelon (i=3)",
"0 (valid boundary)",
"5 (step 10)",
"11 (step 11)",
"16 (step 12)",
"20 (step 13)"
]
],
"row_header": 0
}
],
"animations": {
"knapsack-dp": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-397"
},
{
"id": "step-2",
"frame_id": "source-398"
},
{
"id": "step-3",
"frame_id": "source-399"
},
{
"id": "step-4",
"frame_id": "source-400"
},
{
"id": "step-5",
"frame_id": "source-401"
},
{
"id": "step-6",
"frame_id": "source-402"
},
{
"id": "step-7",
"frame_id": "source-403"
},
{
"id": "step-8",
"frame_id": "source-404"
},
{
"id": "step-9",
"frame_id": "source-405"
},
{
"id": "step-10",
"frame_id": "source-406"
},
{
"id": "step-11",
"frame_id": "source-407"
},
{
"id": "step-12",
"frame_id": "source-408"
},
{
"id": "step-13",
"frame_id": "source-409"
},
{
"id": "step-14",
"frame_id": "source-410"
}
]
}
},
"input_tables": [
0
]
}

View File

@@ -0,0 +1,636 @@
{
"schema_version": 2,
"title": "Single-row space optimization for 0-1 knapsack",
"summary": "Store states in a single one-dimensional array and update capacities in reverse order from high to low so transitions read old values from the previous item's round rather than reusing the same item.",
"context": [
"There are three items—item 1 apple (weight 1, value 5), item 2 pineapple (weight 2, value 11), and item 3 watermelon (weight 3, value 15)—with maximum knapsack capacity 4, and each item may be chosen at most once. Item IDs i start at 1. The weight and value of item i are stored in wgt[i - 1] and val[i - 1].",
"The 6 steps demonstrate only the reverse-order update round for outer loop i = 2 (item 2, pineapple). Before this round begins, the one-dimensional array dp[0..4] holds the results [0, 5, 5, 5, 5] for item 1 alone (apple, i = 1); item 3 (watermelon, i = 3) remains unprocessed throughout this figure. Entry dp[c] gives the maximum value within capacity c using items considered so far without requiring the knapsack to be completely full."
],
"description": [
"When processing the pineapple (weight 2, value 11) at capacity c ≥ 2, compare excluding the pineapple (keeping previous-round value dp[c]) with including it (reading previous-round smaller-capacity value dp[c - 2] + 11), writing the larger value back to dp[c]. Traversing capacities c = 4, 3, 2, 1 in reverse order guarantees that dp[c - 2] to the left has not yet been overwritten in this round and still holds its old state from round i = 1 (apple only).",
"Conversely, updating capacities in forward order from low to high would first update capacity 2 to dp[2] = 11 (already packing one pineapple); evaluating capacity 4 afterward would read dp[2] + 11 = 22, packing the same pineapple twice inside capacity 4 and violating the at-most-once rule of 0-1 knapsack. Reverse-order updates evaluate capacity 4 while dp[2] still holds its old value 5, yielding the correct 5 + 11 = 16.",
"Each frame shows the 4×5 two-dimensional reference table above and the active single-row array dp[0..4] below. In the single row, blue cells indicate retained old states from the previous round (i = 1) and green cells indicate states already updated in the current round (i = 2); at the end of the round, the entire row turns blue to serve as the old states for processing the watermelon next, with no further numeric changes.",
"At each step, the single-row table has separate columns for each capacity's value and the round it represents: i = 1 considers only the apple, i = 2 considers the apple and pineapple, and capacity 0 is always boundary 0. Each step also includes the full two-dimensional reference table, where rows for the first 0, first 1, and first 3 items stay unchanged and zeros at capacities 1 to 4 in row 3 remain uncomputed initial values. Both table captions include the step number for direct lookup by step, capacity, and available items."
],
"result": "After round 2 (i = 2, pineapple) finishes updating in reverse order, the single-row array is dp = [0, 5, 11, 16, 16], where dp[4] = 16 is only the intermediate maximum value at capacity 4 for the first two items (apple and pineapple); item 3 (watermelon, weight 3, value 15) has not yet been processed, so 16 must not be mistaken for the three-item final answer 20. Derived from the input, choosing the apple and watermelon gives weight 1 + 3 = 4 and value 5 + 15 = 20, which is not drawn in this figure.",
"frames": [
{
"id": "source-411",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_comp_step1.png",
"title": "Begin processing the pineapple",
"explanation": "Before round i = 2 (pineapple, weight 2, value 11) starts, single-row dp[0..4] already holds the valid round i = 1 results [0, 5, 5, 5, 5] (apple only) rather than an all-zero table. Capacity 0 is fixed boundary 0, and capacities 1 through 4 hold old round i = 1 states ready for reverse-order updates starting at maximum capacity c = 4.",
"key_state": "Single-row dp = [0, 5, 5, 5, 5]; capacities 1 through 4 hold old i = 1 states, ready to process the pineapple in reverse from c = 4.",
"announcement": "Start round 2 for the pineapple with the single row holding round 1 apple results [0, 5, 5, 5, 5].",
"state_tables": [
{
"caption": "Knapsack space optimization step 1 (begin processing pineapple): single-row dp values and rounds",
"headers": [
"Capacity c",
"Current value",
"Round and status"
],
"rows": [
[
"0",
"0",
"Boundary shared across rounds"
],
[
"1",
"5",
"i = 1, previous round, not yet overwritten"
],
[
"2",
"5",
"i = 1, previous round, not yet overwritten"
],
[
"3",
"5",
"i = 1, previous round, not yet overwritten"
],
[
"4",
"5",
"i = 1, previous round, not yet overwritten"
]
],
"row_header": 0
},
{
"caption": "Knapsack space optimization step 1 (begin processing pineapple): full two-dimensional reference table",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First item only",
"0, valid boundary",
"5, computed",
"5, computed",
"5, computed",
"5, computed"
],
[
"First 2 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-412",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_comp_step2.png",
"title": "Update capacity 4 in reverse order",
"explanation": "Process maximum capacity c = 4 first: excluding the pineapple keeps old value dp[4] = 5; including it reads previous-round old value dp[4 - 2] = dp[2] = 5 (not yet overwritten in this round) plus pineapple value 11 to get 16. Take the larger value to update dp[4] to 16 (round i = 2), while capacities 1, 2, and 3 retain old value 5 from round i = 1. Current single-row dp = [0, 5, 5, 5, 16].",
"key_state": "Entry dp[4] reads old dp[2] = 5 plus 11 to become 16 in round i = 2; capacities 1 to 3 remain 5 from round i = 1; dp = [0, 5, 5, 5, 16].",
"announcement": "Read old value dp[2] = 5 plus 11 to update capacity 4 to 16.",
"state_tables": [
{
"caption": "Knapsack space optimization step 2 (update capacity 4 in reverse): single-row dp values and rounds",
"headers": [
"Capacity c",
"Current value",
"Round and status"
],
"rows": [
[
"0",
"0",
"Boundary shared across rounds"
],
[
"1",
"5",
"i = 1, previous round, not yet overwritten"
],
[
"2",
"5",
"i = 1, previous round, not yet overwritten"
],
[
"3",
"5",
"i = 1, previous round, not yet overwritten"
],
[
"4",
"16",
"i = 2, processed in this round"
]
],
"row_header": 0
},
{
"caption": "Knapsack space optimization step 2 (update capacity 4 in reverse): full two-dimensional reference table",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First item only",
"0, valid boundary",
"5, computed",
"5, computed",
"5, computed",
"5, computed"
],
[
"First 2 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"16, computed"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-413",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_comp_step3.png",
"title": "Update capacity 3 in reverse order",
"explanation": "Continue in reverse to capacity c = 3: excluding the pineapple keeps old value dp[3] = 5; including it reads old value dp[3 - 2] = dp[1] = 5 from round i = 1 plus 11 to get 16. Update dp[3] to 16 (round i = 2), while capacities 1 and 2 keep old state 5 from round i = 1. Current single-row dp = [0, 5, 5, 16, 16].",
"key_state": "Entry dp[3] reads old dp[1] = 5 plus 11 to become 16; capacities 3 and 4 belong to round i = 2, capacities 1 and 2 remain round i = 1; dp = [0, 5, 5, 16, 16].",
"announcement": "Read old value dp[1] = 5 plus 11 to update capacity 3 to 16.",
"state_tables": [
{
"caption": "Knapsack space optimization step 3 (update capacity 3 in reverse): single-row dp values and rounds",
"headers": [
"Capacity c",
"Current value",
"Round and status"
],
"rows": [
[
"0",
"0",
"Boundary shared across rounds"
],
[
"1",
"5",
"i = 1, previous round, not yet overwritten"
],
[
"2",
"5",
"i = 1, previous round, not yet overwritten"
],
[
"3",
"16",
"i = 2, processed in this round"
],
[
"4",
"16",
"i = 2, processed in this round"
]
],
"row_header": 0
},
{
"caption": "Knapsack space optimization step 3 (update capacity 3 in reverse): full two-dimensional reference table",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First item only",
"0, valid boundary",
"5, computed",
"5, computed",
"5, computed",
"5, computed"
],
[
"First 2 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"16, computed",
"16, computed"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-414",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_comp_step4.png",
"title": "Update capacity 2 in reverse order",
"explanation": "Continue in reverse to capacity c = 2: excluding the pineapple keeps old value dp[2] = 5; including it reads boundary dp[2 - 2] = dp[0] = 0 plus 11 to get 11. Update dp[2] to 11 (round i = 2). Because reverse order overwrites dp[2] only now, capacity 4 earlier was able to read the unoverwritten old value dp[2] = 5; only capacity 1 still belongs to round i = 1. Current single-row dp = [0, 5, 11, 16, 16].",
"key_state": "Entry dp[2] reads boundary dp[0] = 0 plus 11 to become 11 (i = 2); only capacity 1 remains 5 from round i = 1; dp = [0, 5, 11, 16, 16].",
"announcement": "Read boundary dp[0] = 0 plus 11 to update capacity 2 to 11; only capacity 1 awaits processing.",
"state_tables": [
{
"caption": "Knapsack space optimization step 4 (update capacity 2 in reverse): single-row dp values and rounds",
"headers": [
"Capacity c",
"Current value",
"Round and status"
],
"rows": [
[
"0",
"0",
"Boundary shared across rounds"
],
[
"1",
"5",
"i = 1, previous round, not yet overwritten"
],
[
"2",
"11",
"i = 2, processed in this round"
],
[
"3",
"16",
"i = 2, processed in this round"
],
[
"4",
"16",
"i = 2, processed in this round"
]
],
"row_header": 0
},
{
"caption": "Knapsack space optimization step 4 (update capacity 2 in reverse): full two-dimensional reference table",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First item only",
"0, valid boundary",
"5, computed",
"5, computed",
"5, computed",
"5, computed"
],
[
"First 2 items",
"0, valid boundary",
"0, uncomputed initial value",
"11, computed",
"16, computed",
"16, computed"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-415",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_comp_step5.png",
"title": "Process capacity 1 where the pineapple does not fit",
"explanation": "Finally process capacity c = 1: because the pineapple weighs 2, exceeding capacity 1, it cannot fit, so the algorithm retains the previous-round value dp[1] = 5. Although dp[1] keeps numeric value 5, capacity 1 has now completed its round 2 (i = 2) check and represents round i = 2 rather than i = 1 (an unchanged number does not mean an unchanged round). Current single-row dp = [0, 5, 11, 16, 16].",
"key_state": "Capacity 1 cannot fit the weight-2 pineapple, keeping value 5 while advancing from round i = 1 to i = 2; all capacities in this round are processed; dp = [0, 5, 11, 16, 16].",
"announcement": "Capacity 1 cannot fit the pineapple, keeping value 5 for round i = 2 and completing round 2.",
"state_tables": [
{
"caption": "Knapsack space optimization step 5 (process capacity 1 where pineapple cannot fit): single-row dp values and rounds",
"headers": [
"Capacity c",
"Current value",
"Round and status"
],
"rows": [
[
"0",
"0",
"Boundary shared across rounds"
],
[
"1",
"5",
"i = 2, processed in this round"
],
[
"2",
"11",
"i = 2, processed in this round"
],
[
"3",
"16",
"i = 2, processed in this round"
],
[
"4",
"16",
"i = 2, processed in this round"
]
],
"row_header": 0
},
{
"caption": "Knapsack space optimization step 5 (process capacity 1 where pineapple cannot fit): full two-dimensional reference table",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First item only",
"0, valid boundary",
"5, computed",
"5, computed",
"5, computed",
"5, computed"
],
[
"First 2 items",
"0, valid boundary",
"5, computed",
"11, computed",
"16, computed",
"16, computed"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-416",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_dp_comp_step6.png",
"title": "Finish the round and prepare for the next round",
"explanation": "All capacities in round 2 (i = 2, pineapple) have been updated, and single-row dp[0..4] = [0, 5, 11, 16, 16] holds all solutions for the first two items. Performing no new calculation, this frame recolors capacities 1 through 4 from green to blue so the entire row is uniformly blue, indicating these round i = 2 results will serve as the old states when round i = 3 processes item 3 (watermelon), which has not yet started.",
"key_state": "Round 2 complete; dp = [0, 5, 11, 16, 16] becomes the old state for the next round; 16 is only the two-item partial result before processing the watermelon.",
"announcement": "Round 2 complete; single-row [0, 5, 11, 16, 16] becomes the old state for processing the watermelon next.",
"state_tables": [
{
"caption": "Knapsack space optimization step 6 (round complete, ready for next round): single-row dp values and rounds",
"headers": [
"Capacity c",
"Current value",
"Round and status"
],
"rows": [
[
"0",
"0",
"Boundary shared across rounds"
],
[
"1",
"5",
"i = 2, processed in this round; serves as old state for next round"
],
[
"2",
"11",
"i = 2, processed in this round; serves as old state for next round"
],
[
"3",
"16",
"i = 2, processed in this round; serves as old state for next round"
],
[
"4",
"16",
"i = 2, processed in this round; serves as old state for next round"
]
],
"row_header": 0
},
{
"caption": "Knapsack space optimization step 6 (round complete, ready for next round): full two-dimensional reference table",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First item only",
"0, valid boundary",
"5, computed",
"5, computed",
"5, computed",
"5, computed"
],
[
"First 2 items",
"0, valid boundary",
"5, computed",
"11, computed",
"16, computed",
"16, computed"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
}
],
"tables": [
{
"caption": "Single-row optimization example: three items with capacity 4",
"headers": [
"Item ID i",
"Item",
"Weight wgt[i - 1]",
"Value val[i - 1]"
],
"rows": [
[
"1",
"Apple",
"1",
"5"
],
[
"2",
"Pineapple",
"2",
"11"
],
[
"3",
"Watermelon",
"3",
"15"
]
],
"row_header": 0
}
],
"animations": {
"knapsack-compressed-row": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-411"
},
{
"id": "step-2",
"frame_id": "source-412"
},
{
"id": "step-3",
"frame_id": "source-413"
},
{
"id": "step-4",
"frame_id": "source-414"
},
{
"id": "step-5",
"frame_id": "source-415"
},
{
"id": "step-6",
"frame_id": "source-416"
}
]
}
},
"input_tables": [
0
]
}

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"title": "0-1 knapsack: optimal selection at capacity 50",
"summary": "Selecting the weight-20 banana and weight-30 grapes from five items fills capacity 50 exactly for a maximum value of 270.",
"context": [
"In 0-1 knapsack, each item may be chosen at most once to maximize total value without exceeding knapsack capacity. This example has 5 items and knapsack capacity cap = 50; item IDs i run from 1 to 5, mapping to array index i - 1 (written wgt[i - 1] and val[i - 1] in the figure's table header)."
],
"description": [
"At the upper left, a table lists the icon, weight, and value of items 1 through 5 (full data in the table below); row 2 (banana) is shaded light orange and row 3 (grapes) is shaded light purple, each sending an arrow to the purple knapsack icon at the upper right labeled \"Knapsack capacity cap = 50\".",
"Below, the result box states \"Maximum value: 270\" and pairs the banana and grapes icons with \"Optimal choice: pack [banana and grapes] into the knapsack using 50 units of capacity in total\"."
],
"frames": [
{
"id": "source-394",
"book_path": "chapter_dynamic_programming/knapsack_problem.assets/knapsack_example.png",
"title": "0-1 knapsack: optimal selection at capacity 50",
"explanation": "Computed from the input data, choosing item 2 (banana) and item 3 (grapes) gives total weight 20 + 30 = 50 and total value 120 + 150 = 270. That is the highest value among all non-overweight subsets—beating, for instance, 260 from items 1 and 4 or 240 from item 5 alone, supplied here from the input table for comparison."
}
],
"tables": [
{
"caption": "Five items for capacity 50; IDs start at 1",
"headers": [
"ID",
"Illustrated item",
"Weight",
"Value",
"Included in optimal choice?"
],
"rows": [
[
"1",
"Apple",
"10",
"50",
"No"
],
[
"2",
"Banana",
"20",
"120",
"Yes"
],
[
"3",
"Grapes",
"30",
"150",
"Yes"
],
[
"4",
"Pineapple",
"40",
"210",
"No"
],
[
"5",
"Watermelon",
"50",
"240",
"No"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,950 @@
{
"schema_version": 2,
"title": "Dynamic programming for coin change",
"summary": "Fill the table cell by cell across coin types and target amounts to find the minimum number of coins that make amount 4 exactly.",
"context": [
"Available coin denominations are 1, 2, and 5 (3 coin types, each usable repeatedly), and the target amount is 4. State dp[i, a] denotes the minimum number of coins needed to make amount a using only the first i coin types; the two-dimensional dp table has 4 rows (i = 0 to 3) and 5 columns (a = 0 to 4).",
"Sentinel MAX = amt + 1 = 5 marks an unreachable (infeasible) amount rather than meaning 5 coins are required. Making amount 0 takes 0 coins, so the first column has boundary value 0; with no coins available (i = 0), every positive amount is unreachable."
],
"description": [
"First allocate a 4×5 all-zero table, then set positive-amount cells dp[0, 1] through dp[0, 4] in the first row to unreachable sentinel MAX = 5 while keeping first-column cells dp[0, 0] through dp[3, 0] at valid boundary 0. Next fill rows i = 1 to 3 across amounts a = 1 to 4: when the current denomination exceeds a, it cannot be used, so inherit dp[i - 1, a] directly above; otherwise compare dp[i - 1, a] above (excluding this coin) with dp[i, a - coins[i - 1]] + 1 to the left in the same row (including one coin of this denomination) and take the smaller value. Reading from the left within the same row allows using the same denomination repeatedly.",
"Each step includes the complete dp state table whose caption names the step number and action, with row headers showing i and available denominations and column headers showing amounts. First-column cells are marked \"boundary set\", first-row infeasible cells are marked \"MAX, unreachable boundary\", cells settled in earlier steps are marked \"computed\", and unevaluated cells are marked \"uncomputed initial value\" and must not be read as solved coin counts. Newly written cells are marked \"written in this step\", and Step 15 marks the bottom-right cell \"return value\" and displays all final entries."
],
"result": "Because denomination 5 exceeds every positive amount 1 through 4 in this table, row 3 simply inherits the two-coin-type results above it. In code, if the final entry equals MAX, -1 is returned to indicate no solution.",
"frames": [
{
"id": "source-426",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step1.png",
"title": "Allocate the initial 4×5 all-zero dp table",
"explanation": "For 3 coin types (denominations 1, 2, 5) and target amount 4, allocate a 4×5 two-dimensional dp table (rows i = 0 to 3, columns a = 0 to 4). Initially every cell defaults to 0: column 0 (amount 0) already holds its valid boundary 0 (0 coins make amount 0), whereas 0 in every positive-amount cell is an uncomputed initial value awaiting Step 2 to set first-row unreachable sentinel MAX.",
"key_state": "Initial 4×5 all-zero table: column 0 holds set boundary 0, positive-amount cells hold uncomputed initial value 0, and first-row MAX boundaries await setup.",
"announcement": "Allocate the initial 4×5 all-zero dp table before setting first-row unreachable sentinel MAX.",
"state_tables": [
{
"caption": "Coin change step 1: full dp table after allocating all-zero table (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 1, denomination 1",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-427",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step2.png",
"title": "Set positive amounts in row 0 to unreachable boundary MAX = 5",
"explanation": "With no coins available (i = 0), no positive amount can be made, so set first-row positive cells dp[0, 1] through dp[0, 4] to unreachable sentinel MAX = 5 (marking infeasibility rather than 5 coins); amount a = 0 requires 0 coins, so first-column cells dp[0, 0] through dp[3, 0] stay at boundary 0. Positive-amount zeros in rows 1 to 3 remain uncomputed initial values.",
"key_state": "Boundaries set: first row dp[0, 1]..dp[0, 4] = MAX (5, unreachable), first column = 0, and 12 interior cells await computation.",
"announcement": "Set first-row positive amounts to unreachable sentinel MAX = 5 while keeping column 0 at boundary 0.",
"state_tables": [
{
"caption": "Coin change step 2: full dp table after boundary initialization (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-428",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step3.png",
"title": "Compute dp[1, 1] (denomination 1, amount 1): minimum 1 coin",
"explanation": "Begin coin type 1 (denomination 1) at amount a = 1 for dp[1, 1]: excluding denomination 1 gives upper dp[0, 1] = MAX (5, unreachable); including 1 coin of denomination 1 takes same-row left boundary dp[1, 0] = 0 plus 1 to get 1. Write the smaller value min(MAX, 1) = 1 to dp[1, 1], corresponding to 1 coin of denomination 1.",
"key_state": "dp[1, 1] (denomination 1, amount 1): min(MAX, dp[1, 0] + 1) = 1, minimum 1 coin.",
"announcement": "Compute dp[1, 1] (denomination 1, amount 1): same-row left dp[1, 0] + 1 gives minimum 1 coin.",
"state_tables": [
{
"caption": "Coin change step 3: full dp table after computing dp[1, 1] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, written in this step",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-429",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step4.png",
"title": "Compute dp[1, 2] (denomination 1, amount 2): minimum 2 coins",
"explanation": "Continue with coin type 1 (denomination 1) at amount a = 2 for dp[1, 2]: excluding it gives upper dp[0, 2] = MAX (unreachable); including 1 coin of denomination 1 reuses same-row left dp[1, 1] = 1 just computed plus 1 to get 2 (two coins of value 1). Write min(MAX, 2) = 2 to dp[1, 2].",
"key_state": "dp[1, 2] (denomination 1, amount 2): min(MAX, dp[1, 1] + 1) = 2, minimum 2 coins.",
"announcement": "Compute dp[1, 2] (denomination 1, amount 2): reuse same-row dp[1, 1] + 1 to write 2 coins.",
"state_tables": [
{
"caption": "Coin change step 4: full dp table after computing dp[1, 2] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, written in this step",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-430",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step5.png",
"title": "Compute dp[1, 3] (denomination 1, amount 3): minimum 3 coins",
"explanation": "Continue with coin type 1 (denomination 1) at amount a = 3 for dp[1, 3]: excluding it gives upper dp[0, 3] = MAX (unreachable); including 1 coin of denomination 1 takes same-row left dp[1, 2] = 2 plus 1 to get 3 (three coins of value 1). Write min(MAX, 3) = 3 to dp[1, 3].",
"key_state": "dp[1, 3] (denomination 1, amount 3): min(MAX, dp[1, 2] + 1) = 3, minimum 3 coins.",
"announcement": "Compute dp[1, 3] (denomination 1, amount 3): take same-row dp[1, 2] + 1 to write 3 coins.",
"state_tables": [
{
"caption": "Coin change step 5: full dp table after computing dp[1, 3] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, written in this step",
"0, uncomputed initial value"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-431",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step6.png",
"title": "Compute dp[1, 4] (denomination 1, amount 4): minimum 4 coins",
"explanation": "Continue with coin type 1 (denomination 1) at amount a = 4 for dp[1, 4]: excluding it gives upper dp[0, 4] = MAX (unreachable); including 1 coin of denomination 1 takes same-row left dp[1, 3] = 3 plus 1 to get 4 (four coins of value 1). Write min(MAX, 4) = 4 to dp[1, 4], completing row 1.",
"key_state": "dp[1, 4] (denomination 1, amount 4): min(MAX, dp[1, 3] + 1) = 4, completing row 1.",
"announcement": "Compute dp[1, 4] (denomination 1, amount 4): same-row dp[1, 3] + 1 gives 4 coins, completing row 1.",
"state_tables": [
{
"caption": "Coin change step 6: full dp table after computing dp[1, 4] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, written in this step"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-432",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step7.png",
"title": "Compute dp[2, 1] (denomination 2, amount 1): denomination too large, inherit 1 coin",
"explanation": "Enter row 2 to introduce coin type 2 (denomination 2) at amount a = 1 for dp[2, 1]. Because denomination 2 exceeds amount 1, a value-2 coin cannot fit, so inherit upper dp[1, 1] = 1 directly and write dp[2, 1] = 1.",
"key_state": "dp[2, 1] (denomination 2, amount 1): denomination 2 exceeds amount 1, so inherit upper dp[1, 1] = 1.",
"announcement": "Compute dp[2, 1] (denomination 2, amount 1): denomination exceeds amount, so inherit 1 from the previous row.",
"state_tables": [
{
"caption": "Coin change step 7: full dp table after computing dp[2, 1] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"1, written in this step",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-433",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step8.png",
"title": "Compute dp[2, 2] (denomination 2, amount 2): take 1 coin of value 2, write 1",
"explanation": "For coin type 2 (denomination 2) at amount a = 2: excluding value-2 coins inherits upper dp[1, 2] = 2 (two coins of value 1); including 1 coin of value 2 takes same-row left boundary dp[2, 0] = 0 plus 1 to get 1 (1 coin of value 2). Write the smaller value min(2, 1) = 1 to dp[2, 2].",
"key_state": "dp[2, 2] (denomination 2, amount 2): min(2, dp[2, 0] + 1) = 1, using 1 coin of value 2.",
"announcement": "Compute dp[2, 2] (denomination 2, amount 2): taking 1 coin of value 2 beats 2 coins without it, so write 1.",
"state_tables": [
{
"caption": "Coin change step 8: full dp table after computing dp[2, 2] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"1, computed",
"1, written in this step",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-434",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step9.png",
"title": "Compute dp[2, 3] (denomination 2, amount 3): 1 plus 2 uses 2 coins",
"explanation": "For coin type 2 (denomination 2) at amount a = 3: excluding value-2 coins gives upper dp[1, 3] = 3 (three coins of value 1); including 1 coin of value 2 takes same-row left dp[2, 1] = 1 (1 coin of value 1) plus 1 to get 2 (1 coin each of values 1 and 2). Write min(3, 2) = 2 to dp[2, 3].",
"key_state": "dp[2, 3] (denomination 2, amount 3): min(3, dp[2, 1] + 1) = 2, combining 1 and 2 for 2 coins.",
"announcement": "Compute dp[2, 3] (denomination 2, amount 3): add one coin of value 2 to the solution dp[2, 1] = 1 and write the minimum count, 2.",
"state_tables": [
{
"caption": "Coin change step 9: full dp table after computing dp[2, 3] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"1, computed",
"1, computed",
"2, written in this step",
"0, uncomputed initial value"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-435",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step10.png",
"title": "Compute dp[2, 4] (denomination 2, amount 4): use another coin of denomination 2; write a count of 2",
"explanation": "For coin type 2 (denomination 2) at amount a = 4: excluding value-2 coins gives upper dp[1, 4] = 4 (four coins of value 1); including a value-2 coin reuses updated same-row left dp[2, 2] = 1 (already holding 1 coin of value 2) plus 1 to get 2 (two coins of value 2). Write min(4, 2) = 2 to dp[2, 4], completing row 2 and showing how same-row left transitions allow reusing the same denomination.",
"key_state": "dp[2, 4] (denomination 2, amount 4): reuse same-row dp[2, 2] + 1 = 2 (two coins of value 2), completing row 2.",
"announcement": "Compute dp[2, 4] (denomination 2, amount 4): reuse same-row dp[2, 2] = 1 plus 1 coin of value 2 to write 2 coins.",
"state_tables": [
{
"caption": "Coin change step 10: full dp table after computing dp[2, 4] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"1, computed",
"1, computed",
"2, computed",
"2, written in this step"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-436",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step11.png",
"title": "Compute dp[3, 1] (denomination 5, amount 1): denomination too large, inherit 1 coin",
"explanation": "Enter row 3 to introduce coin type 3 (denomination 5) at amount a = 1 for dp[3, 1]. Because denomination 5 exceeds amount 1, a value-5 coin cannot fit, so inherit upper dp[2, 1] = 1 directly and write dp[3, 1] = 1.",
"key_state": "dp[3, 1] (denomination 5, amount 1): denomination 5 exceeds amount 1, so inherit upper dp[2, 1] = 1.",
"announcement": "Compute dp[3, 1] (denomination 5, amount 1): denomination 5 exceeds amount 1, inheriting 1 from the previous row.",
"state_tables": [
{
"caption": "Coin change step 11: full dp table after computing dp[3, 1] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"1, computed",
"1, computed",
"2, computed",
"2, computed"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"1, written in this step",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-437",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step12.png",
"title": "Compute dp[3, 2] (denomination 5, amount 2): denomination too large, inherit 1 coin",
"explanation": "Continue with coin type 3 (denomination 5) at amount a = 2: denomination 5 still exceeds amount 2, so a value-5 coin cannot fit; inherit upper dp[2, 2] = 1 directly and write dp[3, 2] = 1.",
"key_state": "dp[3, 2] (denomination 5, amount 2): denomination 5 exceeds amount 2, so inherit upper dp[2, 2] = 1.",
"announcement": "Compute dp[3, 2] (denomination 5, amount 2): denomination 5 exceeds amount 2, inheriting 1 from the previous row.",
"state_tables": [
{
"caption": "Coin change step 12: full dp table after computing dp[3, 2] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"1, computed",
"1, computed",
"2, computed",
"2, computed"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"1, computed",
"1, written in this step",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-438",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step13.png",
"title": "Compute dp[3, 3] (denomination 5, amount 3): denomination too large, inherit 2 coins",
"explanation": "Continue with coin type 3 (denomination 5) at amount a = 3: denomination 5 exceeds amount 3, so a value-5 coin cannot fit; inherit upper dp[2, 3] = 2 directly and write dp[3, 3] = 2.",
"key_state": "dp[3, 3] (denomination 5, amount 3): denomination 5 exceeds amount 3, so inherit upper dp[2, 3] = 2.",
"announcement": "Compute dp[3, 3] (denomination 5, amount 3): denomination 5 exceeds amount 3, inheriting 2 from the previous row.",
"state_tables": [
{
"caption": "Coin change step 13: full dp table after computing dp[3, 3] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"1, computed",
"1, computed",
"2, computed",
"2, computed"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"1, computed",
"1, computed",
"2, written in this step",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-439",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step14.png",
"title": "Compute dp[3, 4] (denomination 5, amount 4): denomination too large, inherit 2 coins",
"explanation": "At bottom-right target amount a = 4 for coin type 3 (denomination 5): because denomination 5 exceeds amount 4, a value-5 coin cannot fit, so inherit upper dp[2, 4] = 2 from the first two coin types (two coins of value 2 making amount 4) and write dp[3, 4] = 2, completing the table.",
"key_state": "dp[3, 4] (denomination 5, amount 4): denomination 5 exceeds amount 4, inheriting upper dp[2, 4] = 2 and completing the table.",
"announcement": "Compute dp[3, 4] (denomination 5, amount 4): denomination 5 exceeds amount 4, inheriting 2 to complete the table.",
"state_tables": [
{
"caption": "Coin change step 14: full dp table after computing dp[3, 4] (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"1, computed",
"1, computed",
"2, computed",
"2, computed"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"1, computed",
"1, computed",
"2, computed",
"2, written in this step"
]
],
"row_header": 0
}
]
},
{
"id": "source-440",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_dp_step15.png",
"title": "Read bottom-right dp[3, 4] and return minimum coin count 2",
"explanation": "With all state transitions complete, read highlighted bottom-right cell dp[3, 4] = 2. Because it differs from unreachable sentinel MAX (5), return 2 directly as the minimum number of coins needed to make amount 4 (using two coins of value 2; if it equaled MAX, -1 would be returned). No cell values change in this step.",
"key_state": "Table complete: bottom-right dp[3, 4] = 2 (two coins of value 2), not equal to MAX, so return 2.",
"announcement": "Table complete; read bottom-right dp[3, 4] and return minimum coin count 2 for amount 4.",
"state_tables": [
{
"caption": "Coin change step 15: full dp table upon returning the result (MAX = 5, unreachable)",
"headers": [
"First i coin types and denominations",
"Amount 0",
"Amount 1",
"Amount 2",
"Amount 3",
"Amount 4"
],
"rows": [
[
"i = 0, no coins",
"0, boundary set",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary",
"MAX, unreachable boundary"
],
[
"i = 1, denomination 1",
"0, boundary set",
"1, computed",
"2, computed",
"3, computed",
"4, computed"
],
[
"i = 2, denominations 1, 2",
"0, boundary set",
"1, computed",
"1, computed",
"2, computed",
"2, computed"
],
[
"i = 3, denominations 1, 2, 5",
"0, boundary set",
"1, computed",
"1, computed",
"2, computed",
"2, return value"
]
],
"row_header": 0
}
]
}
],
"tables": [
{
"caption": "Table-filling example: available coins for target amount 4",
"headers": [
"ID i",
"Denomination"
],
"rows": [
[
"1",
"1"
],
[
"2",
"2"
],
[
"3",
"5"
]
],
"row_header": 0
}
],
"animations": {
"coin-change-dp": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-426"
},
{
"id": "step-2",
"frame_id": "source-427"
},
{
"id": "step-3",
"frame_id": "source-428"
},
{
"id": "step-4",
"frame_id": "source-429"
},
{
"id": "step-5",
"frame_id": "source-430"
},
{
"id": "step-6",
"frame_id": "source-431"
},
{
"id": "step-7",
"frame_id": "source-432"
},
{
"id": "step-8",
"frame_id": "source-433"
},
{
"id": "step-9",
"frame_id": "source-434"
},
{
"id": "step-10",
"frame_id": "source-435"
},
{
"id": "step-11",
"frame_id": "source-436"
},
{
"id": "step-12",
"frame_id": "source-437"
},
{
"id": "step-13",
"frame_id": "source-438"
},
{
"id": "step-14",
"frame_id": "source-439"
},
{
"id": "step-15",
"frame_id": "source-440"
}
]
}
},
"input_tables": [
0
]
}

View File

@@ -0,0 +1,48 @@
{
"schema_version": 2,
"title": "Minimum coin count for coin change",
"summary": "Illustrate an optimal coin selection that makes target amount 11.",
"context": [
"Coin change provides 3 coin denominations coins = [1, 2, 5] in unlimited supply; here the target amount is amt = 11 (distinct from target amount 5 in Coin change II below and target amount 4 in the dynamic programming table). The goal is to find the minimum number of coins that sum to 11."
],
"description": [
"On the left, a table lists ID i and denomination coins[i - 1]; denomination 1 is shaded light orange and denomination 5 is shaded light green, sending arrows for 1 coin and 2 coins into the pouch on the right labeled \"Target amount amt = 11\". Denomination 2 is unused. The table below summarizes these highlights and arrows as coin counts.",
"At the bottom appear \"Optimal coin combination: 1 + 5 + 5\" and \"Minimum number of coins: 3\"."
],
"frames": [
{
"id": "source-424",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_example.png",
"title": "Optimal coin combination for amount 11",
"explanation": "From the illustrated combination, 1 + 5 + 5 = 11 using 3 coins in total. Why 3 is minimal: because the largest denomination is 5, any two coins sum to at most 5 + 5 = 10 < 11, so fewer than 3 coins cannot reach 11 (derived from the input data rather than written in the figure)."
}
],
"tables": [
{
"caption": "Amount 11 example: available denominations and coins used",
"headers": [
"ID i",
"Denomination",
"Coins used in figure"
],
"rows": [
[
"1",
"1",
"1"
],
[
"2",
"2",
"0"
],
[
"3",
"5",
"2"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,80 @@
{
"schema_version": 2,
"title": "Number of coin combinations in coin change II",
"summary": "Using unlimited coins of denominations 1, 2, and 5 to make target amount 5 yields 4 distinct combinations when order is ignored.",
"context": [
"Coin change II likewise provides 3 unlimited denominations [1, 2, 5], but sets target amount amt = 5 and counts how many distinct coin combinations sum to 5 rather than minimizing coin count (arrangements with identical counts per denomination in different orders count as a single combination)."
],
"description": [
"At the upper left, the coin table points via a thick gray rightward arrow to the pouch labeled \"Target amount amt = 5\". Below, the result box reads \"Number of coin combinations: 4\" and lists four coin-addition equations to the right of \"Coin combinations:\".",
"Below, the first table lists the input denominations and the second lists all four combinations in the order drawn, counting coins of each denomination from the equations (that count table is not drawn separately in the figure)."
],
"frames": [
{
"id": "source-425",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/coin_change_ii_example.png",
"title": "Number of coin combinations in coin change II",
"explanation": "Case-by-case check from the input: if denomination 5 is used, only 1 coin of value 5 fits; if denomination 5 is not used, denomination 2 may be used 2, 1, or 0 times, completed by 1, 3, or 5 coins of denomination 1, respectively. That accounts for all four unordered combinations in the table with none missed."
}
],
"tables": [
{
"caption": "Amount 5 combinations example: available coins",
"headers": [
"ID i",
"Denomination"
],
"rows": [
[
"1",
"1"
],
[
"2",
"2"
],
[
"3",
"5"
]
],
"row_header": 0
},
{
"caption": "All combinations making amount 5",
"headers": [
"Combination",
"Count of denomination 1",
"Count of denomination 2",
"Count of denomination 5"
],
"rows": [
[
"1+1+1+1+1",
"5",
"0",
"0"
],
[
"1+1+1+2",
"3",
"1",
"0"
],
[
"1+2+2",
"1",
"2",
"0"
],
[
"5",
"0",
"0",
"1"
]
],
"row_header": 0
}
]
}

View File

@@ -0,0 +1,634 @@
{
"schema_version": 2,
"title": "Single-row update for unbounded knapsack",
"summary": "Update the single-row array in forward order of increasing capacity, reusing the current round's updated solutions at smaller capacities so the same item can be chosen repeatedly.",
"context": [
"The knapsack capacity limit is 4, and all three items may be chosen repeatedly; see the \"Item inputs for forward-order unbounded knapsack updates\" table below for their exact weights and values. Starting after item 1 (apple) has been processed, this example demonstrates only the round for item 2 (pineapple), while item 3 (watermelon) has not yet participated.",
"The two-dimensional state dp[i, c] represents the maximum value achievable using only the first i items with total weight not exceeding capacity c; after space optimization, the single-row array dp[c] (for capacity index c from 0 to 4) overwrites the previous round's results round by round."
],
"description": [
"Round i = 2 traverses capacities c = 1, 2, 3, 4 in forward order. When capacity is too small to fit a pineapple (c < 2), the old value from the previous round is retained; when it fits (c >= 2), the old value dp[c] (excluding the pineapple) is compared against the current-round value dp[c - 2] + 11 (including a pineapple), and the larger value is written to dp[c]. Because smaller positive capacities have already been processed in this round and capacity 0 always remains the valid boundary value 0, reading dp[c - 2] from the left within the same row in forward order allows another pineapple to be added, enabling repeated selection of the same item; the 0-1 knapsack restriction—where each item can be used at most once and old values from the previous round must be read in reverse order—does not apply here.",
"The upper part of the figure shows the two-dimensional table and the lower part shows the single-row array; at each step, the transcript presents the complete state as the single-row table followed by the two-dimensional reference table, with the step number included in both table captions. The single-row table has separate columns for each value and the round that produced it: i = 1 means only apples may be chosen, and i = 2 means apples and pineapples may be chosen, without implying that a solution must include both. Blue indicates states from the previous round, and green indicates entries already processed in the current round; at the end of the round, the current round's results turn blue uniformly to serve as the old states for the next round. In the two-dimensional table, a 0 marked \"uncomputed initial value\" must not be treated as a computed solution."
],
"result": "As an additional comparison using this example's inputs: if reverse order were used by mistake, capacity 4 would be processed before capacity 2 and could only read the old value dp[2] = 10, yielding max(20, 10 + 11) = 21 and missing 22 from two pineapples. Derived from this example's initial array rather than drawn in the figure, this counterexample shows why unbounded knapsack must traverse in forward order to reuse updated values from the current round.",
"frames": [
{
"id": "source-418",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/unbounded_knapsack_dp_comp_step1.png",
"title": "Before traversing i = 2: single row stores the i = 1 solutions",
"explanation": "Before round i = 2 (pineapple) begins, round 1 (only apples available) has already been computed: because apples may be chosen repeatedly, capacities 0 through 4 pack 0 through 4 apples for maximum values of [0, 5, 10, 15, 20]. The single-row array dp currently holds these i = 1 solutions and is ready to process item 2 (pineapple) from left to right in forward order.",
"key_state": "Before round i = 2 starts, single-row dp = [0, 5, 10, 15, 20]. Capacities 1 through 4 all belong to the previous round i = 1 (only apples available); capacity 0 is the boundary.",
"announcement": "Ready to process item 2 (pineapple); the single-row array dp initially holds the round 1 results [0, 5, 10, 15, 20].",
"state_tables": [
{
"caption": "Unbounded knapsack step 1: Before traversing i = 2, single row stores the i = 1 solutions — single-row dp values and round ownership",
"headers": [
"Capacity c",
"Current value",
"Round and available items"
],
"rows": [
[
"0",
"0",
"Capacity 0 boundary shared across rounds"
],
[
"1",
"5",
"Previous round i = 1, only apples available, not yet overwritten"
],
[
"2",
"10",
"Previous round i = 1, only apples available, not yet overwritten"
],
[
"3",
"15",
"Previous round i = 1, only apples available, not yet overwritten"
],
[
"4",
"20",
"Previous round i = 1, only apples available, not yet overwritten"
]
],
"row_header": 0
},
{
"caption": "Unbounded knapsack step 1: Before traversing i = 2, single row stores the i = 1 solutions — two-dimensional reference table of subproblem progress",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First 1 item",
"0, valid boundary",
"5, computed",
"10, computed",
"15, computed",
"20, computed"
],
[
"First 2 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-419",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/unbounded_knapsack_dp_comp_step2.png",
"title": "Process capacity c = 1 in forward order: pineapple does not fit, keep 5",
"explanation": "Start forward-order traversal at capacity c = 1: a pineapple weighs 2, which exceeds capacity 1, so it cannot fit. In the two-dimensional reference table, dp[2, 1] inherits dp[1, 1] = 5 directly from above; in the single-row array, dp[1] keeps the value 5, but now represents the current round i = 2 (highlighted in green in the figure as processed in this round), whereas capacities 2 through 4 remain old values from round i = 1.",
"key_state": "i = 2, c = 1: pineapple of weight 2 does not fit, so dp[1] stays 5. Single-row dp = [0, 5, 10, 15, 20]; capacity 1 now belongs to round i = 2, capacities 2 through 4 still belong to round i = 1, and capacity 0 is the boundary.",
"announcement": "Compute capacity 1 first in forward order: a pineapple of weight 2 does not fit, so dp[1] stays 5 and moves to round i = 2.",
"state_tables": [
{
"caption": "Unbounded knapsack step 2: Process capacity c = 1 in forward order (pineapple does not fit, keep 5) — single-row dp values and round ownership",
"headers": [
"Capacity c",
"Current value",
"Round and available items"
],
"rows": [
[
"0",
"0",
"Capacity 0 boundary shared across rounds"
],
[
"1",
"5",
"Current round i = 2, available items: apple, pineapple"
],
[
"2",
"10",
"Previous round i = 1, only apples available, not yet overwritten"
],
[
"3",
"15",
"Previous round i = 1, only apples available, not yet overwritten"
],
[
"4",
"20",
"Previous round i = 1, only apples available, not yet overwritten"
]
],
"row_header": 0
},
{
"caption": "Unbounded knapsack step 2: Process capacity c = 1 in forward order (pineapple does not fit, keep 5) — two-dimensional reference table of subproblem progress",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First 1 item",
"0, valid boundary",
"5, computed",
"10, computed",
"15, computed",
"20, computed"
],
[
"First 2 items",
"0, valid boundary",
"5, computed",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-420",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/unbounded_knapsack_dp_comp_step3.png",
"title": "Update capacity c = 2 in forward order: include 1 pineapple, update to 11",
"explanation": "Advance rightward in forward order to capacity c = 2: excluding the pineapple keeps the previous round's old value dp[2] = 10 (two apples); including 1 pineapple reads the capacity 0 boundary state dp[0] = 0 to the left in the same row and adds pineapple value 11 to get 11. Taking max(10, 11) = 11 updates single-row dp[2] to the new current-round value 11.",
"key_state": "i = 2, c = 2: max(10, dp[0] + 11) = 11 with boundary dp[0] = 0, so dp[2] is written as 11. Single-row dp = [0, 5, 11, 15, 20]; capacities 1 and 2 belong to round i = 2, capacities 3 and 4 still belong to round i = 1, and capacity 0 is the boundary.",
"announcement": "Update capacity 2 in forward order: choosing 1 pineapple gives value 11, beating 10 from two apples, so dp[2] updates to 11.",
"state_tables": [
{
"caption": "Unbounded knapsack step 3: Update capacity c = 2 in forward order (include 1 pineapple, update to 11) — single-row dp values and round ownership",
"headers": [
"Capacity c",
"Current value",
"Round and available items"
],
"rows": [
[
"0",
"0",
"Capacity 0 boundary shared across rounds"
],
[
"1",
"5",
"Current round i = 2, available items: apple, pineapple"
],
[
"2",
"11",
"Current round i = 2, available items: apple, pineapple"
],
[
"3",
"15",
"Previous round i = 1, only apples available, not yet overwritten"
],
[
"4",
"20",
"Previous round i = 1, only apples available, not yet overwritten"
]
],
"row_header": 0
},
{
"caption": "Unbounded knapsack step 3: Update capacity c = 2 in forward order (include 1 pineapple, update to 11) — two-dimensional reference table of subproblem progress",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First 1 item",
"0, valid boundary",
"5, computed",
"10, computed",
"15, computed",
"20, computed"
],
[
"First 2 items",
"0, valid boundary",
"5, computed",
"11, computed",
"0, uncomputed initial value",
"0, uncomputed initial value"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-421",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/unbounded_knapsack_dp_comp_step4.png",
"title": "Update capacity c = 3 in forward order: apple plus pineapple, update to 16",
"explanation": "Continue in forward order to capacity c = 3: excluding the pineapple gives the previous round's old value dp[3] = 15 (three apples); including 1 pineapple reads dp[1] = 5 (one apple), already processed in this round to the left in the same row, and adds pineapple value 11 to get 16 (one apple plus one pineapple). Taking max(15, 16) = 16 updates dp[3] to 16.",
"key_state": "i = 2, c = 3: max(15, dp[1] + 11) = 16 with dp[1] = 5 from the current round, so dp[3] is written as 16. Single-row dp = [0, 5, 11, 16, 20]; capacities 1 through 3 belong to round i = 2, capacity 4 still belongs to round i = 1, and capacity 0 is the boundary.",
"announcement": "Update capacity 3 in forward order: adding pineapple value 11 to current-row dp[1] = 5 updates dp[3] to 16.",
"state_tables": [
{
"caption": "Unbounded knapsack step 4: Update capacity c = 3 in forward order (apple plus pineapple, update to 16) — single-row dp values and round ownership",
"headers": [
"Capacity c",
"Current value",
"Round and available items"
],
"rows": [
[
"0",
"0",
"Capacity 0 boundary shared across rounds"
],
[
"1",
"5",
"Current round i = 2, available items: apple, pineapple"
],
[
"2",
"11",
"Current round i = 2, available items: apple, pineapple"
],
[
"3",
"16",
"Current round i = 2, available items: apple, pineapple"
],
[
"4",
"20",
"Previous round i = 1, only apples available, not yet overwritten"
]
],
"row_header": 0
},
{
"caption": "Unbounded knapsack step 4: Update capacity c = 3 in forward order (apple plus pineapple, update to 16) — two-dimensional reference table of subproblem progress",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First 1 item",
"0, valid boundary",
"5, computed",
"10, computed",
"15, computed",
"20, computed"
],
[
"First 2 items",
"0, valid boundary",
"5, computed",
"11, computed",
"16, computed",
"0, uncomputed initial value"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-422",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/unbounded_knapsack_dp_comp_step5.png",
"title": "Update capacity c = 4 in forward order: reuse updated current-round value to pick pineapple twice for 22",
"explanation": "Advance in forward order to capacity c = 4: excluding the pineapple gives the previous round's old value dp[4] = 20 (four apples); including a pineapple reads dp[2] = 11 (already containing 1 pineapple), just updated in this round to the left in the same row, and adds 1 more pineapple of value 11 to get 22 (two pineapples in total). Writing max(20, 22) = 22 into dp[4] directly illustrates how forward-order traversal reuses current-round solutions to choose the same item repeatedly.",
"key_state": "i = 2, c = 4: max(20, dp[2] + 11) = 22 with dp[2] = 11 from the current round, so dp[4] is written as 22, corresponding to two pineapples. Single-row dp = [0, 5, 11, 16, 22]; capacities 1 through 4 all belong to round i = 2, and capacity 0 is the boundary.",
"announcement": "Update capacity 4 in forward order: reuse the current-round value dp[2] = 11 plus 11 (two pineapples) to update dp[4] to 22.",
"state_tables": [
{
"caption": "Unbounded knapsack step 5: Update capacity c = 4 in forward order (reuse updated current-round value to pick pineapple twice for 22) — single-row dp values and round ownership",
"headers": [
"Capacity c",
"Current value",
"Round and available items"
],
"rows": [
[
"0",
"0",
"Capacity 0 boundary shared across rounds"
],
[
"1",
"5",
"Current round i = 2, available items: apple, pineapple"
],
[
"2",
"11",
"Current round i = 2, available items: apple, pineapple"
],
[
"3",
"16",
"Current round i = 2, available items: apple, pineapple"
],
[
"4",
"22",
"Current round i = 2, available items: apple, pineapple"
]
],
"row_header": 0
},
{
"caption": "Unbounded knapsack step 5: Update capacity c = 4 in forward order (reuse updated current-round value to pick pineapple twice for 22) — two-dimensional reference table of subproblem progress",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First 1 item",
"0, valid boundary",
"5, computed",
"10, computed",
"15, computed",
"20, computed"
],
[
"First 2 items",
"0, valid boundary",
"5, computed",
"11, computed",
"16, computed",
"22, computed"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
},
{
"id": "source-423",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/unbounded_knapsack_dp_comp_step6.png",
"title": "Finish round i = 2 traversal: single row stores solutions for the first two items",
"explanation": "Forward-order traversal for round i = 2 is complete, and single-row dp = [0, 5, 11, 16, 22] stores the maximum values for capacities 0 through 4 when choosing from the first two items. This step changes no numbers and simply recolors the current round's results uniformly blue to serve as the old states for the next round. In the \"First 3 items\" row of the two-dimensional reference table, the 0 entries at capacities 1 through 4 remain uncomputed initial values while capacity 0 keeps boundary value 0; watermelon has not yet been processed.",
"key_state": "Round i = 2 complete: single-row dp = [0, 5, 11, 16, 22]. Capacities 1 through 4 hold the solutions for the first two items and now turn blue uniformly to serve as old states for the next round; capacity 0 is the boundary, and watermelon has not yet been processed.",
"announcement": "Forward-order update for item 2 (pineapple) is complete; the single-row array stores the solutions [0, 5, 11, 16, 22] for the first two items, and watermelon has not yet been processed.",
"state_tables": [
{
"caption": "Unbounded knapsack step 6: Finish round i = 2 traversal (single row stores solutions for the first two items) — single-row dp values and round ownership",
"headers": [
"Capacity c",
"Current value",
"Round and available items"
],
"rows": [
[
"0",
"0",
"Capacity 0 boundary shared across rounds"
],
[
"1",
"5",
"Current round i = 2, available items: apple, pineapple; will serve as old state for next round"
],
[
"2",
"11",
"Current round i = 2, available items: apple, pineapple; will serve as old state for next round"
],
[
"3",
"16",
"Current round i = 2, available items: apple, pineapple; will serve as old state for next round"
],
[
"4",
"22",
"Current round i = 2, available items: apple, pineapple; will serve as old state for next round"
]
],
"row_header": 0
},
{
"caption": "Unbounded knapsack step 6: Finish round i = 2 traversal (single row stores solutions for the first two items) — two-dimensional reference table of subproblem progress",
"headers": [
"Available items",
"Capacity 0",
"Capacity 1",
"Capacity 2",
"Capacity 3",
"Capacity 4"
],
"rows": [
[
"First 0 items",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary",
"0, valid boundary"
],
[
"First 1 item",
"0, valid boundary",
"5, computed",
"10, computed",
"15, computed",
"20, computed"
],
[
"First 2 items",
"0, valid boundary",
"5, computed",
"11, computed",
"16, computed",
"22, computed"
],
[
"First 3 items",
"0, valid boundary",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value",
"0, uncomputed initial value"
]
],
"row_header": 0
}
]
}
],
"tables": [
{
"caption": "Item inputs for forward-order unbounded knapsack updates",
"headers": [
"ID i",
"Item",
"Weight",
"Value"
],
"rows": [
[
"1",
"Apple",
"1",
"5"
],
[
"2",
"Pineapple",
"2",
"11"
],
[
"3",
"Watermelon",
"3",
"15"
]
],
"row_header": 0
}
],
"animations": {
"unbounded-knapsack-compressed-row": {
"kind": "source-frames",
"states": [
{
"id": "step-1",
"frame_id": "source-418"
},
{
"id": "step-2",
"frame_id": "source-419"
},
{
"id": "step-3",
"frame_id": "source-420"
},
{
"id": "step-4",
"frame_id": "source-421"
},
{
"id": "step-5",
"frame_id": "source-422"
},
{
"id": "step-6",
"frame_id": "source-423"
}
]
}
},
"input_tables": [
0
]
}

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"title": "Unbounded knapsack example: items may be chosen repeatedly",
"summary": "Unbounded knapsack allows choosing items of the same kind repeatedly; the figure shows the optimal selection for capacity 50.",
"context": [
"Given 5 candidate items and knapsack capacity cap = 50, each item may be chosen any number of times provided the total weight does not exceed 50. This figure is a standalone capacity 50 example; the single-row update in Figure 14-23 below switches to capacity 4 and a different dataset of weights 1/2/3 that shares some fruit names but differs in IDs and weights."
],
"description": [
"On the left, a table lists ID i, weight wgt[i-1], and value val[i-1], with a fruit icon identifying each row's item. The apple row is highlighted in light purple and the banana row in light orange, labeled \"×1\" and \"×2\" beside two arrows pointing to the knapsack on the right labeled \"Knapsack capacity cap = 50\". The table below combines the item data with the quantities selected in the figure; 0 for the remaining items means no arrow selects them.",
"At the bottom, the figure explicitly notes \"Maximum value: 290\" and uses fruit icons to show packing one apple and two bananas into the knapsack, using 50 units of capacity in total."
],
"frames": [
{
"id": "source-417",
"book_path": "chapter_dynamic_programming/unbounded_knapsack_problem.assets/unbounded_knapsack_example.png",
"title": "Unbounded knapsack example: items may be chosen repeatedly",
"explanation": "Checking the arithmetic from the input: total weight is 10 + 2 × 20 = 50 and total value is 50 + 2 × 120 = 290, matching the conclusion at the bottom of the figure. If each item could be chosen at most once, the optimal choice for the same input would be banana plus grapes, with weight 20 + 30 = 50 and value 120 + 150 = 270; this comparison is derived from the input rather than drawn in the figure. Allowing repeated selection of bananas raises the maximum value to 290."
}
],
"tables": [
{
"caption": "Unbounded knapsack item data and illustrated selection for capacity 50",
"headers": [
"ID",
"Item",
"Weight",
"Value",
"Selected count in figure"
],
"rows": [
[
"1",
"Apple",
"10",
"50",
"1"
],
[
"2",
"Banana",
"20",
"120",
"2"
],
[
"3",
"Grapes",
"30",
"150",
"0"
],
[
"4",
"Pineapple",
"40",
"210",
"0"
],
[
"5",
"Watermelon",
"50",
"240",
"0"
]
],
"row_header": 0
}
]
}

Some files were not shown because too many files have changed in this diff Show More