{"id":"merge-k-sorted-lists","title":"Merge k Sorted Lists","difficulty":"hard","patterns":["linked-list","heap"],"primaryConcept":"linked-list-merge","concepts":["linked-list-merge","heap-top-k"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"lists","sizeMetric":"node-count","constraints":["sorted-linked-lists","priority-merge"]},"description":"Given an array `lists` where each element is the head of a sorted linked list, merge all lists into one sorted linked list and return its head.","examples":[{"input":"lists = [[1,4,5],[1,3,4],[2,6]]","output":"[1,1,2,3,4,4,5,6]","explanation":"The smallest available head is repeatedly removed from the heap and appended to the result."},{"input":"lists = []","output":"null","explanation":"There are no lists to merge."},{"input":"lists = [[]]","output":"null","explanation":"The only list is empty."}],"constraints":[{"id":"0-lists-length-100","text":"0 <= len(lists) <= 100","check":{"kind":"sizeRange","target":"lists","measure":"arrayLength","min":0,"max":100}},{"id":"0-total-number-of-nodes-10000","text":"0 <= total number of nodes <= 10000","check":{"kind":"sizeRange","target":"lists","measure":"listNodes","min":0,"max":10000}},{"id":"10000-node-val-10000","text":"-10000 <= Node.val <= 10000","check":{"kind":"valueRange","target":"lists","selector":"listValues","min":-10000,"max":10000}},{"id":"each-linked-list-is-sorted-in-non-decreasing-order","text":"Each linked list is sorted in non-decreasing order","check":{"kind":"ordering","target":"lists","order":"nondecreasing","selector":"listValues"}}],"starterCode":"# TraceCode provides ListNode at runtime.\n# class ListNode:\n#     def __init__(self, val=0, next=None):\n#         self.val = val\n#         self.next = next\n\nclass Solution:\n    def mergeKLists(self, lists):\n        # Your code here\n        pass","functionName":"mergeKLists","testCases":[{"id":"1","input":{"lists":[{"val":1,"next":{"val":4,"next":{"val":5,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},"__type__":"ListNode"},{"val":1,"next":{"val":3,"next":{"val":4,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},"__type__":"ListNode"},{"val":2,"next":{"val":6,"next":null,"__type__":"ListNode"},"__type__":"ListNode"}]},"expected":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":2,"next":{"__type__":"ListNode","val":3,"next":{"__type__":"ListNode","val":4,"next":{"__type__":"ListNode","val":4,"next":{"__type__":"ListNode","val":5,"next":{"__type__":"ListNode","val":6,"next":null}}}}}}}},"description":"Canonical three-list merge."},{"id":"2","input":{"lists":[]},"expected":null,"description":"No lists."},{"id":"3","input":{"lists":[null]},"expected":null,"description":"Only an empty list."},{"id":"4","input":{"lists":[{"val":-3,"next":{"val":-1,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},{"val":-2,"next":{"val":2,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},null]},"expected":{"__type__":"ListNode","val":-3,"next":{"__type__":"ListNode","val":-2,"next":{"__type__":"ListNode","val":-1,"next":{"__type__":"ListNode","val":2,"next":null}}}},"description":"Negative values with an empty list mixed in."},{"id":"5","input":{"lists":[{"val":1,"next":{"val":1,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},{"val":1,"next":null,"__type__":"ListNode"}]},"expected":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":1,"next":null}}},"description":"Duplicate values across lists."},{"id":"h1","input":{"lists":[{"val":5,"next":null,"__type__":"ListNode"},{"val":1,"next":{"val":2,"next":{"val":4,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},"__type__":"ListNode"}]},"expected":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":2,"next":{"__type__":"ListNode","val":4,"next":{"__type__":"ListNode","val":5,"next":null}}}},"description":"Short list starts after a longer list's head."},{"id":"h2","input":{"lists":[{"val":-10,"next":{"val":0,"next":{"val":10,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},"__type__":"ListNode"},{"val":-10,"next":{"val":-5,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},{"val":11,"next":null,"__type__":"ListNode"}]},"expected":{"__type__":"ListNode","val":-10,"next":{"__type__":"ListNode","val":-10,"next":{"__type__":"ListNode","val":-5,"next":{"__type__":"ListNode","val":0,"next":{"__type__":"ListNode","val":10,"next":{"__type__":"ListNode","val":11,"next":null}}}}}},"description":"Ties at the smallest value."},{"id":"h3","input":{"lists":[{"val":1,"next":{"val":2,"next":{"val":3,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},"__type__":"ListNode"}]},"expected":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":2,"next":{"__type__":"ListNode","val":3,"next":null}}}},{"id":"h4","input":{"lists":[null,{"val":0,"next":null,"__type__":"ListNode"},null]},"expected":{"__type__":"ListNode","val":0,"next":null}},{"id":"h5","input":{"lists":[{"val":-3,"next":{"val":-1,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},{"val":-2,"next":{"val":2,"next":null,"__type__":"ListNode"},"__type__":"ListNode"},{"val":1,"next":{"val":1,"next":null,"__type__":"ListNode"},"__type__":"ListNode"}]},"expected":{"__type__":"ListNode","val":-3,"next":{"__type__":"ListNode","val":-2,"next":{"__type__":"ListNode","val":-1,"next":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":2,"next":null}}}}}}},{"id":"topup-boundary-values","input":{"lists":[null,{"__type__":"ListNode","val":-10000,"next":null},{"__type__":"ListNode","val":10000,"next":null}]},"expected":{"__type__":"ListNode","val":-10000,"next":{"__type__":"ListNode","val":10000,"next":null}},"description":"Minimum and maximum node values with an empty list mixed in."},{"id":"topup-uneven-interleave","input":{"lists":[{"__type__":"ListNode","val":0,"next":{"__type__":"ListNode","val":2,"next":{"__type__":"ListNode","val":2,"next":null}}},{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":3,"next":null}}},{"__type__":"ListNode","val":-1,"next":{"__type__":"ListNode","val":4,"next":null}}]},"expected":{"__type__":"ListNode","val":-1,"next":{"__type__":"ListNode","val":0,"next":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":2,"next":{"__type__":"ListNode","val":2,"next":{"__type__":"ListNode","val":3,"next":{"__type__":"ListNode","val":4,"next":null}}}}}}}},"description":"Uneven list lengths with repeated values interleaved across lists."},{"id":"topup-all-empty-lists","input":{"lists":[null,null,null]},"expected":null,"description":"Multiple empty input lists still produce an empty merged list."},{"id":"topup-many-singletons","input":{"lists":[{"__type__":"ListNode","val":5,"next":null},{"__type__":"ListNode","val":1,"next":null},{"__type__":"ListNode","val":3,"next":null},{"__type__":"ListNode","val":2,"next":null},{"__type__":"ListNode","val":4,"next":null}]},"expected":{"__type__":"ListNode","val":1,"next":{"__type__":"ListNode","val":2,"next":{"__type__":"ListNode","val":3,"next":{"__type__":"ListNode","val":4,"next":{"__type__":"ListNode","val":5,"next":null}}}}},"description":"Many one-node lists require ordering by heap head rather than list position."}],"hints":[{"level":1,"content":"At any moment, the next output node must be the smallest current head among all non-empty lists.","revealPattern":false},{"level":2,"content":"Use a min-heap keyed by node value to choose the next list head efficiently.","revealPattern":true},{"level":3,"content":"Push each initial head. Repeatedly pop the smallest node, append it, and push that node's next pointer when it exists.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation gives a good balance of clarity and performance?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"heap","name":"Min-heap of current heads","summary":"Keep one candidate node per non-empty list in a min-heap.","decisionReason":"Only k nodes can be the next smallest, one head per list, and the heap holds exactly those k. Each of the N nodes passes through the heap once at log k per pop, and k stays small next to N.","complexity":{"time":"O(N log k)","space":"O(k)"},"tradeoffs":["Runs in O(N log k) time and uses O(k) space."],"isOptimal":true,"steps":["Push each non-empty list head","Pop the smallest current node","Append it to the result tail","Push its successor if one exists"]},{"id":"pairwise","name":"Repeated pairwise merge","summary":"Merge lists two at a time until one list remains.","decisionReason":"Each merge pass re-walks nodes that earlier passes already ordered: the first list's nodes get re-compared in every one of the k-1 merges, which is where the kN cost comes from.","complexity":{"time":"O(kN)","space":"O(1)"},"tradeoffs":["Runs in O(kN) time and uses O(1) space."],"isOptimal":false,"steps":["Merge list 0 and list 1","Merge that result with list 2","Repeat until all lists are consumed"]},{"id":"flatten-sort","name":"Flatten and sort","summary":"Read every value into an array, sort it, then build a new list.","decisionReason":"Sorting from scratch ignores that every list is already sorted. N log N re-derives order the input already had, and the whole array has to sit in memory first.","complexity":{"time":"O(N log N)","space":"O(N)"},"tradeoffs":["Runs in O(N log N) time and uses O(N) space."],"isOptimal":false,"steps":["Copy every node value","Sort the copied values","Build a new linked list"]}]},"codingCheckpoints":[{"id":"init-output","title":"Create result anchor","description":"Create a dummy output node and a tail cursor so appends do not lose the result head.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"initializes_merge_dummy_anchor","scope":"dummy-node","readMode":"linked-list-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"initializes_merge_tail_from_dummy","scope":"curr-pointer","readMode":"linked-list-value-query-v1"}]}]},"commonMistakes":["Appending without a stable dummy anchor","Advancing the only reference to the result head"],"hint":"Use a dummy node and keep a separate moving tail cursor.","semanticSpec":{"intent":"Create stable output state before heap nodes are appended.","doneWhen":"A dummy node exists and a tail cursor is seeded from it.","shouldFailWhen":"There is no stable anchor for the merged list.","roles":["dummy node","output tail"],"mustProve":["A dummy output anchor is allocated.","A tail cursor starts at that anchor."],"mustNotAccept":["Using only one moving result cursor."]}},{"id":"seed-heap","title":"Seed heap with list heads","description":"Push each non-null list head into the min-heap before merging begins.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"seeds_heap_from_input_values","scope":"seed-heap","readMode":"heap-value-query-v1"}]},"commonMistakes":["Forgetting to skip null heads","Starting the merge loop with an empty heap"],"hint":"The heap should initially contain at most one node from each non-empty list.","semanticSpec":{"intent":"Make every non-empty list compete by inserting its head into the priority structure.","doneWhen":"The code scans the input list heads and inserts each available head into the heap.","shouldFailWhen":"The heap is initialized but never seeded from the input lists.","roles":["input lists","current head","min-heap"],"mustProve":["The input list collection is scanned.","Non-null heads are pushed into the heap."],"mustNotAccept":["Only creating an empty heap.","Pushing a fixed placeholder instead of list heads."]}},{"id":"pop-smallest","title":"Pop the smallest head","description":"While the heap is non-empty, remove the node with the smallest value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"extracts_heap_values","scope":"heap-pop","readMode":"heap-value-query-v1"}]},"commonMistakes":["Peeking without removing the node","Using a max-heap ordering"],"hint":"Each loop iteration should consume exactly one heap frontier node.","semanticSpec":{"intent":"Select and consume the smallest current list head.","doneWhen":"The merge loop extracts a heap value for the node to append.","shouldFailWhen":"The loop never removes a heap entry.","roles":["heap","selected node","merge loop"],"mustProve":["A priority extract operation drives the selected node."],"mustNotAccept":["Only reading the heap top without consuming it."],"proofSnippets":[{"id":"py-merge-k-pop-smallest","language":"python","code":"class Solution:\n    def mergeKLists(self, lists):\n        import heapq\n        heap = []\n        for i, node in enumerate(lists):\n            if node:\n                heapq.heappush(heap, (node.val, i, node))\n        dummy = ListNode()\n        curr = dummy\n        while heap:\n            value, i, node = heapq.heappop(heap)"}]}},{"id":"append-node","title":"Append popped node","description":"Attach the popped node to the result tail, then advance the tail.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"appends_existing_node_to_output_tail","scope":"append-node","readMode":"linked-list-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"advances_output_tail_after_append","scope":"append-node","readMode":"linked-list-value-query-v1"}]}]},"commonMistakes":["Creating a new value node instead of reusing the popped node","Forgetting to advance the output tail"],"hint":"After `tail.next = node`, move `tail` to `tail.next`.","semanticSpec":{"intent":"Extend the merged linked list with the selected heap node.","doneWhen":"The output tail points to the popped node and then advances to that node.","shouldFailWhen":"The popped node is not linked into the output chain or the tail stays in place.","roles":["output tail","popped node"],"mustProve":["The tail next pointer receives the selected node.","The tail cursor advances after the append."],"mustNotAccept":["Dropping the popped node.","Appending but leaving the tail cursor unchanged."],"proofSnippets":[{"id":"py-merge-k-append-node","language":"python","code":"class Solution:\n    def mergeKLists(self, lists):\n        import heapq\n        heap = []\n        for i, node in enumerate(lists):\n            if node:\n                heapq.heappush(heap, (node.val, i, node))\n        dummy = ListNode()\n        curr = dummy\n        while heap:\n            value, i, node = heapq.heappop(heap)\n            curr.next = node\n            curr = curr.next"}]}},{"id":"push-next","title":"Push successor node","description":"If the popped node has a successor, push that successor into the heap.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"reinserts_projected_heap_values","scope":"push-next","readMode":"heap-value-query-v1"}]},"commonMistakes":["Pushing every remaining node at once","Forgetting to push the successor"],"hint":"Only the list that produced the popped node advances by one step.","semanticSpec":{"intent":"Refill the heap frontier from the same list whose head was just consumed.","doneWhen":"The code checks the popped node's next pointer and inserts that successor into the heap.","shouldFailWhen":"Successor nodes are never returned to the heap.","roles":["popped node","successor node","heap"],"mustProve":["The successor is projected from the extracted node.","That successor is inserted back into the heap."],"mustNotAccept":["Never pushing node.next.","Pushing an unrelated list head."],"proofSnippets":[{"id":"py-merge-k-push-next","language":"python","code":"class Solution:\n    def mergeKLists(self, lists):\n        import heapq\n        heap = []\n        for i, node in enumerate(lists):\n            if node:\n                heapq.heappush(heap, (node.val, i, node))\n        dummy = ListNode()\n        curr = dummy\n        while heap:\n            value, i, node = heapq.heappop(heap)\n            curr.next = node\n            curr = curr.next\n            if node.next:\n                heapq.heappush(heap, (node.next.val, i, node.next))"}]}},{"id":"return-result","title":"Return merged head","description":"Return the node after the dummy anchor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"returns_output_head_from_dummy_next","scope":"return-result","readMode":"linked-list-value-query-v1"}]},"commonMistakes":["Returning the dummy node itself","Returning the moving tail cursor"],"hint":"The dummy is not part of the answer; return `dummy.next`.","semanticSpec":{"intent":"Expose the merged list without the sentinel anchor.","doneWhen":"The function returns the next pointer of the dummy output node.","shouldFailWhen":"The sentinel itself or the final tail is returned.","roles":["dummy node","merged head"],"mustProve":["The returned value is anchored at dummy.next."],"mustNotAccept":["Returning the dummy node.","Returning the heap or tail."],"proofSnippets":[{"id":"py-merge-k-return-result","language":"python","code":"class Solution:\n    def mergeKLists(self, lists):\n        import heapq\n        heap = []\n        for i, node in enumerate(lists):\n            if node:\n                heapq.heappush(heap, (node.val, i, node))\n        dummy = ListNode()\n        curr = dummy\n        while heap:\n            value, i, node = heapq.heappop(heap)\n            curr.next = node\n            curr = curr.next\n            if node.next:\n                heapq.heappush(heap, (node.next.val, i, node.next))\n        return dummy.next"}]}}],"slides":[{"id":"read-the-problem","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Merge k sorted lists into one","workspacePanel":"problem","body":["You are handed the heads of k sorted linked lists and you weave their nodes into a single sorted list, reusing the existing nodes instead of copying values.","Only the current head of each sorted list can be the next output node. Taking one head exposes exactly one new candidate from that same list."]},{"id":"scan-heads-baseline","kind":"code-trace","chapter":"The problem","eyebrow":"The obvious way","title":"Scan all k heads for the smallest, every single step","summary":"Comparing heads is the right instinct for two lists. With k of them this version re-reads all k heads each time it wants one node, so watch how much of that reading repeats.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def chooseHead(a: ListNode, b: ListNode | None, c: ListNode | None, curr: ListNode) -> ListNode:\n    best = a\n    if b is not None and b.val < best.val:\n        best = b\n    if c is not None and c.val < best.val:\n        best = c\n    curr.next = best\n    return curr.next","steps":[{"id":"scan-first","title":"Read all three heads to find the smallest","codeLine":5,"summary":"The heads are 1, 1, and 2. The code reads all three to decide that list 0’s 1 is smallest and goes first.","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":0},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•"],"current":0}]}},{"id":"attach-first","title":"Attach the winner and advance only that list","codeLine":7,"summary":"List 0’s 1 is attached and list 0 advances to 4. Lists 1 and 2 still hold their original heads.","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":1},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•",1],"current":1}]}},{"id":"scan-again","title":"Read all three heads again from scratch","codeLine":5,"summary":"The heads are now 4, 1, and 2. The code re-reads all three even though only list 0’s head changed since the last node.","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":1},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•",1],"current":1}]}},{"id":"attach-again","title":"List 1’s 1 wins this read","codeLine":7,"summary":"List 1’s 1 is attached and list 1 advances to 3. The next node will read all three heads once more.","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":1},{"name":"list 1","values":[1,3,4],"current":1},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•",1,1],"current":2}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let best = a;\nif (b !== null && b.val < best.val) {\n    best = b;\n}\nif (c !== null && c.val < best.val) {\n    best = c;\n}\ncurr.next = best;\nreturn curr.next;","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":8,"8":9},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let best = a;\nif (b !== null && b.val < best.val) {\n    best = b;\n}\nif (c !== null && c.val < best.val) {\n    best = c;\n}\ncurr.next = best;\nreturn curr.next;","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":8,"8":9},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"ListNode best = a;\nif (b != null && b.val < best.val) {\n    best = b;\n}\nif (c != null && c.val < best.val) {\n    best = c;\n}\ncurr.next = best;\nreturn curr.next;","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":8,"8":9},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"ListNode best = a;\nif (b != null && b.val < best.val) {\n    best = b;\n}\nif (c != null && c.val < best.val) {\n    best = c;\n}\ncurr.next = best;\nreturn curr.next;","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":8,"8":9},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"ListNode* best = a;\nif ((b != nullptr && b->val < best->val)) {\n    best = b;\n}\nif ((c != nullptr && c->val < best->val)) {\n    best = c;\n}\ncurr->next = best;\nreturn curr->next;","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":8,"8":9},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7}}}}},"body":["Each output node costs a fresh read of all k heads, even the heads that did not change."]},{"id":"scan-cost","kind":"case-probe","chapter":"The problem","eyebrow":"Count the work","title":"How much does choosing each output node cost when there are k lists?","workspacePanel":"trace","summary":"Every output node triggers a full pass over all k heads to find the smallest.","options":[{"id":"k-each","label":"About k comparisons per node, so roughly N times k overall","rationale":"Each of the N output nodes re-scans all k heads, so the total is about N times k. With many lists that k factor on every single node is the waste, and most of each scan re-reads heads that did not move.","isCorrect":true},{"id":"constant","label":"A constant amount, the heads are right there","rationale":"Reading one head is constant, but finding the smallest means checking all k of them, and that whole scan repeats for every output node."},{"id":"log","label":"About log k per node, lists are sorted","rationale":"A linear scan does not get the log automatically. Sorted lists let you skip work inside one list, but choosing among k current heads still reads all k unless you keep them in a smarter structure."}],"answer":"About k per node, so roughly N times k in total. Each output node re-scans all k heads, and most of that pass re-reads heads that never moved since the last scan."},{"id":"what-repeats","kind":"case-probe","chapter":"The idea","eyebrow":"Find the waste","title":"Between two output steps, how many of the k heads actually changed?","workspacePanel":"visualizer","summary":"You just popped list 0’s head and advanced it; the other lists were left untouched.","options":[{"id":"one","label":"Only one: the list you just took from","rationale":"You consume exactly one node per step, so only that list advances. The other k minus 1 heads are identical to what the previous scan already compared, so re-reading them is pure repeat work.","isCorrect":true},{"id":"all","label":"All of them shift forward together","rationale":"Only the list that supplied the node advances; the rest keep their front node for the next comparison, so most heads are unchanged."},{"id":"none","label":"None, the heads only change at the end","rationale":"One head changes every step, the one whose node you just placed. The point is that just one changes, not zero."}],"answer":"Only one head changes per step, the list you just took from. The other k minus 1 are exactly what the last scan saw, so the linear re-scan keeps re-deriving the same comparisons.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"what-repeats","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":1},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•",1],"current":1}]}}]}},{"id":"which-structure","kind":"case-probe","chapter":"The idea","eyebrow":"Find the structure","title":"You want the smallest of the k current heads, and only one head changes each step. What holds them?","workspacePanel":"visualizer","summary":"You need the minimum of the k front values now, and after each pop you swap out one value and ask again.","options":[{"id":"min-heap","label":"A min-heap of the k current front values","rationale":"A heap surfaces its smallest at the root for free and absorbs a single replacement in log k, so popping the minimum and pushing the one new head costs log k instead of a fresh scan of all k. That is the move from N times k down to N log k.","isCorrect":true},{"id":"sorted-list","label":"A fully sorted list of the k heads, re-sorted each step","rationale":"Keeping all k heads in full sorted order is more than you need: you only ever read the smallest, and re-sorting after each swap costs more than a heap’s log k repair."},{"id":"plain-array","label":"A plain array of heads, same as before","rationale":"A plain array gives no faster way to find the minimum than scanning it, so this is the N times k version again with no improvement."}],"answer":"A min-heap of the k current front values. The root is always the next node to append, and replacing one head after a pop costs log k, which turns the per-node k scan into a log k update.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"which-structure","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":0},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0}]}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which structure should choose the next node?","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"Which implementation gives a good balance of clarity and performance?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"heap","name":"Min-heap of current heads","summary":"Keep one candidate node per non-empty list in a min-heap.","decisionReason":"Only k nodes can be the next smallest, one head per list, and the heap holds exactly those k. Each of the N nodes passes through the heap once at log k per pop, and k stays small next to N.","complexity":{"time":"O(N log k)","space":"O(k)"},"tradeoffs":["Runs in O(N log k) time and uses O(k) space."],"isOptimal":true,"steps":["Push each non-empty list head","Pop the smallest current node","Append it to the result tail","Push its successor if one exists"]},{"id":"pairwise","name":"Repeated pairwise merge","summary":"Merge lists two at a time until one list remains.","decisionReason":"Each merge pass re-walks nodes that earlier passes already ordered: the first list's nodes get re-compared in every one of the k-1 merges, which is where the kN cost comes from.","complexity":{"time":"O(kN)","space":"O(1)"},"tradeoffs":["Runs in O(kN) time and uses O(1) space."],"isOptimal":false,"steps":["Merge list 0 and list 1","Merge that result with list 2","Repeat until all lists are consumed"]},{"id":"flatten-sort","name":"Flatten and sort","summary":"Read every value into an array, sort it, then build a new list.","decisionReason":"Sorting from scratch ignores that every list is already sorted. N log N re-derives order the input already had, and the whole array has to sit in memory first.","complexity":{"time":"O(N log N)","space":"O(N)"},"tradeoffs":["Runs in O(N log N) time and uses O(N) space."],"isOptimal":false,"steps":["Copy every node value","Sort the copied values","Build a new linked list"]}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":0},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0}],"heap":{"values":[1,1,2],"name":"front-value heap","current":0}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"The heap root is always the next node","workspacePanel":"visualizer","body":["Seed the heap with the front value of each non-empty list, then repeat one move: pop the smallest, append that node to the merged tail, and push the next value from the same list.","Watch [1, 4, 5], [1, 3, 4], and [2, 6]. The heap starts holding 1, 1, and 2, and its root settles the order one pop at a time."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":0},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•"],"current":0}],"heap":{"values":[1,1,2],"name":"front-value heap","current":0}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Trace the heap","title":"Merge [1, 4, 5], [1, 3, 4], [2, 6]","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pop-first","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":0},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•"],"current":0}],"heap":{"values":[1,1,2],"name":"front-value heap","current":0,"highlighted":[1,2]}}},{"id":"pop-second","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":1},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•",1],"current":1}],"heap":{"values":[1,2,4],"name":"front-value heap","current":0,"highlighted":[1,2]}}},{"id":"pop-third","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":1},{"name":"list 1","values":[1,3,4],"current":1},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•",1,1],"current":2}],"heap":{"values":[2,3,4],"name":"front-value heap","current":0,"highlighted":[1,2]}}},{"id":"pop-fourth","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":1},{"name":"list 1","values":[1,3,4],"current":1},{"name":"list 2","values":[2,6],"current":1},{"name":"merged","values":["•",1,1,2],"current":3}],"heap":{"values":[3,4,6],"name":"front-value heap","current":0,"highlighted":[1,2]}}}]},"beats":[{"id":"pop-first","title":"The heap holds 1, 1, 2. Which node is appended, and what is pushed back?","summary":"The heap has one 1 from list 0 and one 1 from list 1.","prompt":"One heap pop takes a single node.","options":[{"id":"pop-1-push-4","label":"Append list 0’s 1, then push its next value 4","rationale":"The root is the smallest, a 1, so it is appended and list 0 advances. Only list 0 produced that node, so only its next value, 4, is pushed, giving a heap of 1, 2, 4.","isCorrect":true},{"id":"pop-both-ones","label":"Append both 1s at once, since they tie","rationale":"Each pop yields one node. The two 1s are appended on separate steps; ties do not collapse into a single move."},{"id":"push-all","label":"Append the 1 and push every list’s next value","rationale":"Only the list that produced the popped node advances, so just list 0’s 4 is pushed; the other lists keep their current heads."}],"answer":"Append list 0’s 1 and push its next value 4. One pop, one append, and only the popped node’s own list contributes the replacement, leaving 1, 2, 4 in the heap."},{"id":"pop-second","title":"The heap is now 1, 2, 4. What comes out next?","summary":"List 0 already gave up its first 1.","prompt":"The smallest value still wins, and only its own list refills the heap.","options":[{"id":"pop-1-push-3","label":"Append list 1’s 1, then push its next value 3","rationale":"The root 1 is appended and list 1 advances, so 3 is pushed. The heap becomes 2, 3, 4, and the merged list is now 1, 1.","isCorrect":true},{"id":"pop-2","label":"Append the 2, it is list 2’s turn","rationale":"The heap still holds a smaller value, list 1’s 1, at the root; 2 cannot be next while a 1 is present."},{"id":"pop-4","label":"Append the 4 from list 0","rationale":"The heap root is list 1's 1, so 4 waits behind the smaller head."}],"answer":"Append list 1’s 1 and push 3. The second tie value comes out one step after the first, and the heap settles to 2, 3, 4."},{"id":"pop-third","title":"With the heap at 2, 3, 4, which node is appended?","summary":"The merged list currently holds 1, 1.","prompt":"Read the heap root and the list it came from.","options":[{"id":"pop-2-push-6","label":"Append the 2, then push list 2’s next value 6","rationale":"The root 2 is smallest, so it is appended and list 2 advances to 6. The heap becomes 3, 4, 6 and the merged list is 1, 1, 2.","isCorrect":true},{"id":"pop-3","label":"Append the 3 from list 1","rationale":"The 2 is smaller than the 3, so the heap surfaces the 2 first."},{"id":"push-2-again","label":"Append the 2 and re-push list 1’s value","rationale":"The popped node came from list 2. Its successor is 6, so list 1's value stays where it is."}],"answer":"Append the 2 and push list 2’s next value 6. The popped node’s own list refills the heap, which becomes 3, 4, 6."},{"id":"pop-fourth","title":"The heap is 3, 4, 6. What is appended, and what refills the heap?","summary":"The merged list currently holds 1, 1, 2.","prompt":"Read the heap root and the list it came from.","options":[{"id":"pop-3-push-4","label":"Append the 3, then push list 1’s next value 4","rationale":"The root 3 is appended and list 1 advances to 4, so 4 is pushed. The heap holds 4, 4, 6 and the merged list reads 1, 1, 2, 3, with 4, 4, 5, 6 still to come.","isCorrect":true},{"id":"pop-4","label":"Append a 4, the lists are full of 4s now","rationale":"The smallest in 3, 4, 6 is the 3, so it must come out before either 4."},{"id":"done","label":"Nothing, the merge is finished","rationale":"The heap is still non-empty, so the loop continues; the merge ends only when the heap is empty."}],"answer":"Append the 3 and push list 1’s next value 4. The same one-pop-one-push rhythm carries the merge to its end, 1, 1, 2, 3, 4, 4, 5, 6."}]},{"id":"forget-push-next-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"Can we pop and append without pushing the popped node’s next?","summary":"Seeding the heap and popping the smallest both look complete, and the first few nodes come out in order. Watch what is still sitting in the lists once the loop stops.","pitfall":"The loop below pops the smallest and appends it, but never pushes the next value from the list it just consumed.","whyItMatters":"Without pushing the popped node’s successor, each list only ever offers its seeded head. The heap drains to empty after just k pops, so merging [1, 4, 5], [1, 3, 4], [2, 6] returns 1 → 1 → 2 and silently drops 3, 4, 4, 5, 6. After appending a node, push that same list’s next value so the list keeps competing.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def mergeKLists(lists: list[ListNode | None]) -> ListNode | None:\n    import heapq\n    heap: list[int] = []\n    for node in lists:\n        if node is not None:\n            heapq.heappush(heap, node.val)\n    dummy = ListNode(0)\n    curr = dummy\n    while heap:\n        smallest = heapq.heappop(heap)\n        curr.next = ListNode(smallest)\n        curr = curr.next\n    return dummy.next","steps":[{"id":"seed","title":"Seed the heap with the three heads 1, 1, 2","codeLine":6,"summary":"Each list contributes its front value, so the heap holds 1, 1, 2 and nothing else.","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":0},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•"],"current":0}],"heap":{"values":[1,1,2],"name":"front-value heap","current":0,"highlighted":[1,2]}}},{"id":"pop-three","title":"Three pops drain the seeded heads into the result","codeLine":10,"summary":"Popping the two 1s and the 2 appends 1, 1, 2, but no successor was ever pushed, so the heap is now empty.","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":1},{"name":"list 1","values":[1,3,4],"current":1},{"name":"list 2","values":[2,6],"current":1},{"name":"merged","values":["•",1,1,2],"current":3}],"heap":{"values":[],"name":"front-value heap","current":0}}},{"id":"lost","title":"The loop ends with 3, 4, 4, 5, 6 still in the lists","codeLine":13,"summary":"The empty heap stops the loop, so it returns 1 → 1 → 2 and the rest of every list is dropped.","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":1},{"name":"list 1","values":[1,3,4],"current":1},{"name":"list 2","values":[2,6],"current":1},{"name":"merged","values":["•",1,1,2],"current":3}],"heap":{"values":[],"name":"front-value heap","current":0}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const heap = new MinHeap();\nfor (const node of lists) {\n    if (node !== null) {\n        heap.push(node.val);\n    }\n}\nconst dummy = new ListNode(0, null);\nlet curr = dummy;\nwhile (heap.size() > 0) {\n    const smallest = heap.pop();\n    curr.next = new ListNode(smallest, null);\n    curr = curr.next;\n}\nreturn dummy.next;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14},"statementBundles":{"6":{"startLine":4,"endLine":6},"12":{"startLine":12,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const heap: MinHeap<number> = new MinHeap<number>();\nfor (const node of lists) {\n    if (node !== null) {\n        heap.push(node.val);\n    }\n}\nconst dummy = new ListNode(0, null);\nlet curr = dummy;\nwhile (heap.size() > 0) {\n    const smallest = heap.pop()!;\n    curr.next = new ListNode(smallest, null);\n    curr = curr.next;\n}\nreturn dummy.next;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14},"statementBundles":{"6":{"startLine":4,"endLine":6},"12":{"startLine":12,"endLine":13}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"PriorityQueue<Integer> heap = new PriorityQueue<>();\nfor (ListNode node : lists) {\n    if (node != null) {\n        heap.offer(node.val);\n    }\n}\nListNode dummy = new ListNode(0);\nListNode curr = dummy;\nwhile (!heap.isEmpty()) {\n    int smallest = heap.poll();\n    curr.next = new ListNode(smallest);\n    curr = curr.next;\n}\nreturn dummy.next;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14},"statementBundles":{"6":{"startLine":4,"endLine":6},"12":{"startLine":12,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"PriorityQueue<int, int> heap = new();\nforeach (var node in lists) {\n    if (node != null) {\n        heap.Enqueue(node.val, node.val);\n    }\n}\nListNode dummy = new(0, null);\nListNode curr = dummy;\nwhile (heap.Count > 0) {\n    int smallest = heap.Dequeue();\n    curr.next = new ListNode(smallest);\n    curr = curr.next;\n}\nreturn dummy.next;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14},"statementBundles":{"6":{"startLine":4,"endLine":6},"12":{"startLine":12,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> heap;\nfor (ListNode* node : lists) {\n    if (node != nullptr) {\n        heap.push_back(node->val); push_heap(heap.begin(), heap.end(), greater<>());\n    }\n}\nListNode* dummy = new ListNode(0, nullptr);\nListNode* curr = dummy;\nwhile (!heap.empty()) {\n    int smallest = heapPopValue(heap);\n    curr->next = new ListNode(smallest, nullptr);\n    curr = curr->next;\n}\nreturn dummy->next;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14},"statementBundles":{"6":{"startLine":4,"endLine":6},"12":{"startLine":12,"endLine":13}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The pop-append-push loop handled three healthy lists cleanly. The inputs that stress it are the ones that change what gets seeded into the heap at the start.","Two are worth tracing: a null list mixed in among real ones, and a set of lists that are all empty."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":0},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0}],"heap":{"values":[1,1,2],"name":"front-value heap","current":0}}}]}},{"id":"edge-null-list","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"One of the input lists is null. What goes into the heap for it?","workspacePanel":"visualizer","summary":"lists = [null, 0->null, null]. Only one list has a node.","options":[{"id":"skip","label":"Nothing: a null list seeds no value, so the heap holds only 0","rationale":"A null list has no front value to compare, so seeding skips it. The heap starts with just the single 0, which pops as the whole merged list.","isCorrect":true},{"id":"push-null","label":"A null placeholder, to keep one entry per list","rationale":"Pushing a null has no value to order against and would break the heap comparison; null lists are simply skipped at seeding."},{"id":"zero","label":"A 0, as a stand-in for the empty list","rationale":"Inventing a 0 would inject a value the input never had and corrupt the merged result; a null list contributes nothing."}],"answer":"Nothing. A null list has no head to seed, so it is skipped and the heap holds only the real node 0, which becomes the entire merged list.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-null-list","state":{"arrays":[{"name":"list 0","values":[]},{"name":"list 1","values":[0],"current":0},{"name":"list 2","values":[]},{"name":"merged","values":["•"],"current":0}],"heap":{"values":[0],"name":"front-value heap","current":0}}}]}},{"id":"edge-all-empty","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"What is returned when every input list is empty?","workspacePanel":"visualizer","summary":"lists = [null, null, null]. Nothing seeds the heap.","options":[{"id":"null","label":"null: the heap is never seeded, so the loop never runs","rationale":"With every list null, no front value is pushed, the heap starts empty, and the while loop is skipped. The dummy’s next was never set, so dummy.next is null.","isCorrect":true},{"id":"dummy","label":"The dummy node itself","rationale":"The dummy is a throwaway anchor; you return dummy.next, which here is null because nothing was ever appended."},{"id":"empty-heap-error","label":"It fails trying to pop an empty heap","rationale":"The loop only runs while the heap is non-empty, so an empty heap means zero iterations rather than a bad pop."}],"answer":"null. No list seeds a value, so the heap stays empty, the loop is skipped, and dummy.next is never assigned.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-all-empty","state":{"arrays":[{"name":"list 0","values":[]},{"name":"list 1","values":[]},{"name":"list 2","values":[]},{"name":"merged","values":["•"],"current":0}],"heap":{"values":[],"name":"front-value heap","current":0}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Build the heap-driven merge","workspacePanel":"visualizer","ctaLabel":"Start coding","summary":"The pop-append-push loop is the whole merge.","body":["Anchor the output at a dummy node, then seed a min-heap with the front value of every non-empty list. While the heap has nodes, pop the smallest, append it to the tail, and push the next value from the list it came from.","When the heap empties, every node has been placed in order, and the answer is everything after the dummy."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"arrays":[{"name":"list 0","values":[1,4,5],"current":0},{"name":"list 1","values":[1,3,4],"current":0},{"name":"list 2","values":[2,6],"current":0},{"name":"merged","values":["•"],"current":0}],"heap":{"values":[1,1,2],"name":"front-value heap","current":0,"highlighted":[1,2]}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the heap-driven k-way merge","summary":"Now build it: anchor the output at a dummy with a tail cursor, seed the heap with each non-empty list's head, then on each pop append the smallest to the tail and push that node's successor, and at the end return the node after the dummy.","workspacePanel":"code","checkpoints":[{"id":"init-output","title":"Create result anchor","description":"Create a dummy output node and a tail cursor so appends do not lose the result head.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"initializes_merge_dummy_anchor","scope":"dummy-node","readMode":"linked-list-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"initializes_merge_tail_from_dummy","scope":"curr-pointer","readMode":"linked-list-value-query-v1"}]}]},"commonMistakes":["Appending without a stable dummy anchor","Advancing the only reference to the result head"],"hint":"Use a dummy node and keep a separate moving tail cursor.","semanticSpec":{"intent":"Create stable output state before heap nodes are appended.","doneWhen":"A dummy node exists and a tail cursor is seeded from it.","shouldFailWhen":"There is no stable anchor for the merged list.","roles":["dummy node","output tail"],"mustProve":["A dummy output anchor is allocated.","A tail cursor starts at that anchor."],"mustNotAccept":["Using only one moving result cursor."]}},{"id":"seed-heap","title":"Seed heap with list heads","description":"Push each non-null list head into the min-heap before merging begins.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"seeds_heap_from_input_values","scope":"seed-heap","readMode":"heap-value-query-v1"}]},"commonMistakes":["Forgetting to skip null heads","Starting the merge loop with an empty heap"],"hint":"The heap should initially contain at most one node from each non-empty list.","semanticSpec":{"intent":"Make every non-empty list compete by inserting its head into the priority structure.","doneWhen":"The code scans the input list heads and inserts each available head into the heap.","shouldFailWhen":"The heap is initialized but never seeded from the input lists.","roles":["input lists","current head","min-heap"],"mustProve":["The input list collection is scanned.","Non-null heads are pushed into the heap."],"mustNotAccept":["Only creating an empty heap.","Pushing a fixed placeholder instead of list heads."]}},{"id":"pop-smallest","title":"Pop the smallest head","description":"While the heap is non-empty, remove the node with the smallest value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"extracts_heap_values","scope":"heap-pop","readMode":"heap-value-query-v1"}]},"commonMistakes":["Peeking without removing the node","Using a max-heap ordering"],"hint":"Each loop iteration should consume exactly one heap frontier node.","semanticSpec":{"intent":"Select and consume the smallest current list head.","doneWhen":"The merge loop extracts a heap value for the node to append.","shouldFailWhen":"The loop never removes a heap entry.","roles":["heap","selected node","merge loop"],"mustProve":["A priority extract operation drives the selected node."],"mustNotAccept":["Only reading the heap top without consuming it."],"proofSnippets":[{"id":"py-merge-k-pop-smallest","language":"python","code":"class Solution:\n    def mergeKLists(self, lists):\n        import heapq\n        heap = []\n        for i, node in enumerate(lists):\n            if node:\n                heapq.heappush(heap, (node.val, i, node))\n        dummy = ListNode()\n        curr = dummy\n        while heap:\n            value, i, node = heapq.heappop(heap)"}]}},{"id":"append-node","title":"Append popped node","description":"Attach the popped node to the result tail, then advance the tail.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"appends_existing_node_to_output_tail","scope":"append-node","readMode":"linked-list-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"advances_output_tail_after_append","scope":"append-node","readMode":"linked-list-value-query-v1"}]}]},"commonMistakes":["Creating a new value node instead of reusing the popped node","Forgetting to advance the output tail"],"hint":"After `tail.next = node`, move `tail` to `tail.next`.","semanticSpec":{"intent":"Extend the merged linked list with the selected heap node.","doneWhen":"The output tail points to the popped node and then advances to that node.","shouldFailWhen":"The popped node is not linked into the output chain or the tail stays in place.","roles":["output tail","popped node"],"mustProve":["The tail next pointer receives the selected node.","The tail cursor advances after the append."],"mustNotAccept":["Dropping the popped node.","Appending but leaving the tail cursor unchanged."],"proofSnippets":[{"id":"py-merge-k-append-node","language":"python","code":"class Solution:\n    def mergeKLists(self, lists):\n        import heapq\n        heap = []\n        for i, node in enumerate(lists):\n            if node:\n                heapq.heappush(heap, (node.val, i, node))\n        dummy = ListNode()\n        curr = dummy\n        while heap:\n            value, i, node = heapq.heappop(heap)\n            curr.next = node\n            curr = curr.next"}]}},{"id":"push-next","title":"Push successor node","description":"If the popped node has a successor, push that successor into the heap.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"reinserts_projected_heap_values","scope":"push-next","readMode":"heap-value-query-v1"}]},"commonMistakes":["Pushing every remaining node at once","Forgetting to push the successor"],"hint":"Only the list that produced the popped node advances by one step.","semanticSpec":{"intent":"Refill the heap frontier from the same list whose head was just consumed.","doneWhen":"The code checks the popped node's next pointer and inserts that successor into the heap.","shouldFailWhen":"Successor nodes are never returned to the heap.","roles":["popped node","successor node","heap"],"mustProve":["The successor is projected from the extracted node.","That successor is inserted back into the heap."],"mustNotAccept":["Never pushing node.next.","Pushing an unrelated list head."],"proofSnippets":[{"id":"py-merge-k-push-next","language":"python","code":"class Solution:\n    def mergeKLists(self, lists):\n        import heapq\n        heap = []\n        for i, node in enumerate(lists):\n            if node:\n                heapq.heappush(heap, (node.val, i, node))\n        dummy = ListNode()\n        curr = dummy\n        while heap:\n            value, i, node = heapq.heappop(heap)\n            curr.next = node\n            curr = curr.next\n            if node.next:\n                heapq.heappush(heap, (node.next.val, i, node.next))"}]}},{"id":"return-result","title":"Return merged head","description":"Return the node after the dummy anchor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"linked-list","fact":"returns_output_head_from_dummy_next","scope":"return-result","readMode":"linked-list-value-query-v1"}]},"commonMistakes":["Returning the dummy node itself","Returning the moving tail cursor"],"hint":"The dummy is not part of the answer; return `dummy.next`.","semanticSpec":{"intent":"Expose the merged list without the sentinel anchor.","doneWhen":"The function returns the next pointer of the dummy output node.","shouldFailWhen":"The sentinel itself or the final tail is returned.","roles":["dummy node","merged head"],"mustProve":["The returned value is anchored at dummy.next."],"mustNotAccept":["Returning the dummy node.","Returning the heap or tail."],"proofSnippets":[{"id":"py-merge-k-return-result","language":"python","code":"class Solution:\n    def mergeKLists(self, lists):\n        import heapq\n        heap = []\n        for i, node in enumerate(lists):\n            if node:\n                heapq.heappush(heap, (node.val, i, node))\n        dummy = ListNode()\n        curr = dummy\n        while heap:\n            value, i, node = heapq.heappop(heap)\n            curr.next = node\n            curr = curr.next\n            if node.next:\n                heapq.heappush(heap, (node.next.val, i, node.next))\n        return dummy.next"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Keep a min-heap of the current front value from each list; its root is the next node, and after each pop the same list pushes its successor.","workspacePanel":"code","body":["The min-heap wins because it refuses to repeat comparisons that did not change: only one head moves per step, so the heap absorbs that single update in log k instead of re-reading all k heads.","Each of the N nodes is popped once and triggers one push, so the work is O(N log k) and the heap never holds more than k entries, down from the O(N times k) of scanning every head each step."],"takeaways":[{"title":"The heap root is the next node","body":"A min-heap of the k current front values always surfaces the global smallest unmerged node at its root, so one pop chooses each output node."},{"title":"Only the popped list refills the heap","body":"After appending a node, push that same list’s next value, because just one list advanced; pushing nothing drains the heap early and drops the rest."},{"title":"A dummy anchor frees the head","body":"Building from a throwaway dummy makes every append identical and lets you return dummy.next as the real merged head."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
